Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

Faces2 (#144)

Rory Clear5f0f5d407c3f
diff --git a/adaface.py b/adaface.py
index e4acf51..582be83 100644
--- a/adaface.py
+++ b/adaface.py
@@ -91,5 +91,6 @@ class ADAFACE():
x = self.linear(x)
x = self.bn2(x)
norm = Tensor.sqrt(Tensor.sum(x * x, keepdim=True))
+ #norm = 10
output = x / norm
- return output, norm
\ No newline at end of file
+ return output
\ No newline at end of file
diff --git a/blazeface.py b/blazeface.py
index b1a38f7..84722b8 100644
--- a/blazeface.py
+++ b/blazeface.py
@@ -182,15 +182,13 @@ class BlazeFace():
detections = self._tensors_to_detections(out[0], out[1], self.anchors)
- detections = Tensor.cat(detections[:, :4], detections[:, 16:17], dim=1)
-
detections = self.postprocess(detections)[0]
detections = detections * 256
detections[:, [0, 2]] -= pad_top # ymin, ymax
detections[:, [1, 3]] -= pad_left # xmin, xmax
detections /= scale
- return detections[:, :5]
+ return detections
def _tensors_to_detections(self, raw_box_tensor, raw_score_tensor, anchors):
detection_boxes = self._decode_boxes(raw_box_tensor, anchors) # (B, N, 16)
@@ -227,7 +225,7 @@ class BlazeFace():
boxes = boxes.unsqueeze(0)
max_det = 896
iou_threshold = 0.3
- probs = boxes[:, :, 4]
+ probs = boxes[:, :, 16]
order_all = Tensor.topk(probs, min(max_det, probs.shape[1]))[1]
batch_idx = Tensor.arange(order_all.shape[0]).reshape(-1, 1)
boxes = boxes[batch_idx, order_all]
@@ -235,7 +233,7 @@ class BlazeFace():
ious = Tensor.triu(ious, diagonal=1)
high_iou_mask = (ious > iou_threshold)
no_overlap_mask = high_iou_mask.sum(axis=1) == 0
- conf_mask = (boxes[:, :, 4] >= self.min_score_thresh)
+ conf_mask = (boxes[:, :, 16] >= self.min_score_thresh)
final_mask = no_overlap_mask * conf_mask
return boxes * final_mask.unsqueeze(-1)
diff --git a/clearcam.py b/clearcam.py
index 3419fe9..edeef9e 100644
--- a/clearcam.py
+++ b/clearcam.py
@@ -656,7 +656,7 @@ def run_clip(return_q, clip, im, top_k, cam_name, selected_dir, is_face):
class HLSRequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
- self.clip = kwargs.pop('clip_instance', None)
+ self.object_finder = kwargs.pop('clip_instance', None)
super().__init__(*args, **kwargs)
def log_message(self, format, *args): pass # don't print stuff
@@ -1051,6 +1051,7 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
start = data.get("start")
count = data.get("count")
is_face = data.get("is_face") or False
+ if is_face and not use_face: return
if start is None: start, count = 0, 100
uploaded_image = data.get("uploaded_image")
if uploaded_image:
@@ -1074,21 +1075,21 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
})
selected_dirs.append("video")
- if image_text and use_clip: self.clip._load_all_embeddings()
- if (uploaded_image or similar_img) and use_clip: self.clip._load_all_embeddings(face=is_face)
+ if image_text and use_clip: self.object_finder._load_all_embeddings()
+ if (uploaded_image or similar_img) and (use_clip or use_face): self.object_finder._load_all_embeddings(face=is_face)
- if uploaded_image and use_clip:
- results = self.server.process_with_clip_lock(run_clip, self.clip, uploaded_image, start+count, cam_name, selected_dir, is_face)
+ if uploaded_image and (use_clip or is_face):
+ results = self.server.process_with_clip_lock(run_clip, self.object_finder, uploaded_image, start+count, cam_name, selected_dir, is_face)
self.send_results(results, start, count)
return
- if similar_img and use_clip:
- results = self.server.process_with_clip_lock(run_clip, self.clip, similar_img, start+count, cam_name, selected_dir, is_face) # todo one with above
+ if similar_img and (use_clip or is_face):
+ results = self.server.process_with_clip_lock(run_clip, self.object_finder, similar_img, start+count, cam_name, selected_dir, is_face) # todo one with above
self.send_results(results, start, count)
return
if image_text and use_clip:
- results = self.server.process_with_clip_lock(run_search, self.clip, image_text, start+count, cam_name, selected_dir)
+ results = self.server.process_with_clip_lock(run_search, self.object_finder, image_text, start+count, cam_name, selected_dir)
self.send_results(results, start, count)
return
@@ -1231,7 +1232,7 @@ cams = dict()
active_subprocesses = []
import socket
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
- def __init__(self, server_address, use_clip, RequestHandlerClass):
+ def __init__(self, server_address, use_clip, face, RequestHandlerClass):
ThreadingMixIn.__init__(self)
HTTPServer.__init__(self, server_address, RequestHandlerClass)
self.cleanup_stop_event = threading.Event()
@@ -1241,28 +1242,28 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
database.run_put("max_storage", "all", 256)
max_gb = database.run_get("max_storage", None)
self.max_gb = max_gb["all"]
- self.clip = CachedCLIPSearch(prewarm=True) if use_clip else None
- self.clip_stop_event = threading.Event()
- self.clip_thread = None
+ self.object_finder = ObjectFinder(prewarm=True, clip=use_clip, face=face) if (use_clip or face) else None
+ self.object_finder_stop_event = threading.Event()
+ self.object_finder_thread = None
self._setup_cleanup_and_clip_thread()
- self.clip_lock = threading.Lock()
+ self.object_finder_lock = threading.Lock()
def process_with_clip_lock(self, func, *args):
- if not self.clip_lock.acquire(timeout=30):
- self.send_error(429, "CLIP processor busy, try again later")
- return None
+ if not self.object_finder_lock.acquire(timeout=30):
+ self.send_error(429, "CLIP processor busy, try again later")
+ return None
try:
- return_q = multiprocessing.Queue()
- p = multiprocessing.Process(target=func, args=(return_q, *args))
- p.start()
- results = return_q.get(timeout=3600)
- p.join()
- return results
+ return_q = multiprocessing.Queue()
+ p = multiprocessing.Process(target=func, args=(return_q, *args))
+ p.start()
+ results = return_q.get(timeout=300)
+ p.join()
+ return results
finally:
- self.clip_lock.release()
+ self.object_finder_lock.release()
def finish_request(self, request, client_address):
- self.RequestHandlerClass(request, client_address, self, clip_instance=self.clip)
+ self.RequestHandlerClass(request, client_address, self, clip_instance=self.object_finder)
def _setup_cleanup_and_clip_thread(self):
if self.cleanup_thread is None or not self.cleanup_thread.is_alive():
@@ -1270,10 +1271,10 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
self.cleanup_thread = threading.Thread(target=self._cleanup_task, daemon=True, name="StorageCleanup")
self.cleanup_thread.start()
- if use_clip and (self.clip_thread is None or not self.clip_thread.is_alive()):
- self.clip_stop_event.clear()
- self.clip_thread = threading.Thread(target=self._clip_task, daemon=True, name="CLIPMaintenance")
- self.clip_thread.start()
+ if (use_clip or use_face) and (self.object_finder_thread is None or not self.object_finder_thread.is_alive()):
+ self.object_finder_stop_event.clear()
+ self.object_finder_thread = threading.Thread(target=self._objects_task, daemon=True, name="CLIPMaintenance")
+ self.object_finder_thread.start()
def _cleanup_task(self):
while not self.cleanup_stop_event.is_set():
@@ -1283,15 +1284,15 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
print(f"Cleanup error: {e}")
self.cleanup_stop_event.wait(timeout=600)
- def _clip_task(self):
- while not self.clip_stop_event.is_set():
+ def _objects_task(self):
+ while not self.object_finder_stop_event.is_set():
try:
- object_folders = self.clip.find_object_folders("data/cameras")
+ object_folders = self.object_finder.find_object_folders("data/cameras")
for folder in object_folders:
name = folder.split("/")[2]
vod = is_vod(name)
if vod and name in database.run_get("analysis_prog", None) and database.run_get("analysis_prog", None)[name]["Tracking"] < 100: continue
- embeddings, batch_paths = self.clip.precompute_embeddings(folder, vod=vod, database=database, cam_name=name, userID=userID, key=key)
+ embeddings, batch_paths = self.object_finder.precompute_embeddings(folder, vod=vod, database=database, cam_name=name, userID=userID, key=key)
alerts = database.run_get("alerts", name)
if userID:
for path, embedding in zip(batch_paths, embeddings):
@@ -1312,12 +1313,12 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
# todo, move to own loop
for k, alert in alerts.items():
if alert.desc is not None and alert.desc_emb is None:
- alert.desc_emb = self.process_with_clip_lock(run_encode_text, self.clip, alert.desc)
+ alert.desc_emb = self.process_with_clip_lock(run_encode_text, self.object_finder, alert.desc)
database.run_put("alerts", name, alert, id=k)
except Exception as e:
print(f"CLIP error: {e}")
- self.clip_stop_event.wait(timeout=1)
+ self.object_finder_stop_event.wait(timeout=1)
def _check_and_cleanup_storage(self):
total_size = sum(f.stat().st_size for f in (BASE_DIR / "cameras").glob('**/*') if f.is_file())
@@ -1368,9 +1369,9 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
if hasattr(self, 'cleanup_thread') and self.cleanup_thread:
self.cleanup_thread.join(timeout=5)
if hasattr(self, 'clip_stop_event'):
- self.clip_stop_event.set()
- if hasattr(self, 'clip_thread') and self.clip_thread:
- self.clip_thread.join(timeout=5)
+ self.object_finder_stop_event.set()
+ if hasattr(self, 'clip_thread') and self.object_finder_thread:
+ self.object_finder_thread.join(timeout=5)
super().server_close()
@@ -1386,6 +1387,8 @@ if __name__ == "__main__":
key = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--key=")), None)
use_clip = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--use_clip=")), None)
if use_clip: use_clip = use_clip != "False" # str to bool
+ use_face = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--use_face=")), None)
+ if use_face: use_face = use_face != "False" # str to bool
model_variant = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--yolo_size=")), None)
yolo_res = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--yolo_res=")), 640)
if not model_variant:
@@ -1393,23 +1396,25 @@ if __name__ == "__main__":
if model_variant < 6:
yolo_ress = {"1":320, "2":640, "3":960,"4":1280,"5":1536}
yolo_res = yolo_ress[input("\nSelect a YOLOV9 resoltuion from \n1: 320\n2: 640\n3: 960\n4: 1280\n5: 1536\nor press enter to skip (defaults to 960):") or "3"]
- use_clip = input("Would you like to use clip search on events? (y/n) (1.7GB model), or press enter to skip:") or False
+ use_clip = input("Would you like to enable clip search on events? (y/n) (1.7GB model), or press enter to skip:") or False
use_clip = use_clip in ["y", "Y"]
+ use_face = input("Would you like to enable (experimental) face recognition search? (y/n), or press enter to skip:") or False
+ use_face = use_face in ["y", "Y"]
if url is None and userID is None:
userID = input("enter your Clearcam user id or press Enter to skip: ")
if len(userID) > 0:
key = ""
while len(key) < 1: key = input("enter a password for encryption: ")
- sys.argv.extend([f"--use_clip={use_clip}" ,f"--userid={userID}", f"--key={key}", f"--yolo_size={model_variant}"])
+ sys.argv.extend([f"--use_clip={use_clip}", f"--use_face={use_face}" ,f"--userid={userID}", f"--key={key}", f"--yolo_size={model_variant}"])
else: userID = None
if userID is not None and key is None:
print("Error: key is required when userID is provided")
sys.exit(1)
- if use_clip:
- from clip import CachedCLIPSearch
+ if use_clip or use_face:
+ from objects import ObjectFinder
cam_name = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--cam_name=")), "my_camera")
@@ -1434,7 +1439,7 @@ if __name__ == "__main__":
try:
try:
- server = ThreadedHTTPServer(('0.0.0.0', 8080), use_clip, HLSRequestHandler)
+ server = ThreadedHTTPServer(('0.0.0.0', 8080), use_clip=use_clip, face=use_face, RequestHandlerClass=HLSRequestHandler)
print(f"Serving at http://{get_lan_ip()}:8080")
except OSError as e:
if e.errno == socket.errno.EADDRINUSE:
diff --git a/mainview.html b/mainview.html
index 8c46e42..2df86a6 100644
--- a/mainview.html
+++ b/mainview.html
@@ -1360,18 +1360,16 @@
<polyline points="21 15 16 10 5 21"></polyline>
</svg>
</label>
- <!-- todo add back for face
<label for="faceUpload" style="cursor: pointer; padding: 6px 12px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); display: flex; align-items: center; justify-content: center;" title="Search by face">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="8" r="4"></circle>
<path d="M6 20c0-4 3-6 6-6s6 2 6 6"></path>
</svg>
</label>
- -->
<input type="file" id="faceUpload" accept="image/*" style="display: none;">
<span class="tooltip">
<span class="tooltip-icon">?</span>
- <span class="tooltiptext">Upload an image to find similar objects in your footage.</span>
+ <span class="tooltiptext">Use an image or face to find similar objects in your footage.</span>
</span>
<input type="file" id="imageUpload" accept="image/*" style="display: none;">
</div>
@@ -3094,7 +3092,7 @@
image_text: null,
similar_img: null,
uploaded_image: null,
- is_face: false, // todo use is_face when ready
+ is_face: is_face,
};
payload.start = eventStart;
payload.count = EVENT_PAGE_SIZE;
diff --git a/clip.py b/objects.py
similarity index 75%
rename from clip.py
rename to objects.py
index c0304a9..387a93f 100644
--- a/clip.py
+++ b/objects.py
@@ -144,25 +144,30 @@ def encode_text(model, text):
x = x @ model.text_projection
return x / (x * x).sum(axis=-1, keepdim=True).sqrt()
-class CachedCLIPSearch:
- def __init__(self, prewarm=False, base_path="data/cameras"):
+class ObjectFinder:
+ def __init__(self, prewarm=False, base_path="data/cameras", clip=False, face=False):
self.base_path = base_path
self.image_embeddings = {}
self.face_embeddings = {}
self.image_paths = {}
self.face_paths = {}
+ self.clip = clip
+ self.face = face
- self.model = OpenCLIP()
-
- #self.blazeface = BlazeFace()
- #self.adaface = ADAFACE()
+ if self.clip: self.model = OpenCLIP()
+
+ if self.face:
+ self.blazeface = BlazeFace()
+ self.adaface = ADAFACE()
# prewarm
if prewarm:
- #blazeface_jit(self.blazeface, Tensor.rand((640, 640, 3)).cast(dtype=dtypes.uchar))
- #adaface_jit(self.adaface, Tensor.rand((112, 112, 3)).cast(dtype=dtypes.uchar))
- precompute_embeddings_jit(self.model, Tensor.rand((1, 3, 224, 224), dtype=dtypes.float32))
- precompute_embeddings_jit(self.model, Tensor.rand((16, 3, 224, 224), dtype=dtypes.float32))
+ if self.face:
+ blazeface_jit(self.blazeface, Tensor.rand((640, 640, 3)).cast(dtype=dtypes.uchar))
+ adaface_jit(self.adaface, Tensor.rand((112, 112, 3)).cast(dtype=dtypes.uchar))
+ if self.clip:
+ precompute_embeddings_jit(self.model, Tensor.rand((1, 3, 224, 224), dtype=dtypes.float32))
+ precompute_embeddings_jit(self.model, Tensor.rand((16, 3, 224, 224), dtype=dtypes.float32))
def find_object_folders(self, base_path="data/cameras"):
object_folders = []
@@ -180,7 +185,6 @@ class CachedCLIPSearch:
# db for progress
def precompute_embeddings(self, folder_path, batch_size=16, vod=False, database=None, cam_name=None, userID=None, key=None):
folder_embeddings, folder_paths = get_embeddings(folder_path, "embeddings.pkl")
- folder_embeddings_face, folder_paths_face = get_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl")
current_images = {
os.path.join(folder_path, f)
@@ -188,24 +192,35 @@ class CachedCLIPSearch:
if f.lower().endswith((".png", ".jpg", ".jpeg"))
}
+ if self.face:
+ folder_embeddings_face, folder_paths_face = get_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl")
+ cached_images_face = set(folder_embeddings_face.keys())
+ new_images_face = current_images - cached_images_face
+ deleted_images_face = cached_images_face - current_images
+
+ for img in deleted_images_face:
+ folder_embeddings_face.pop(img, None)
+ folder_embeddings_face.pop(img, None)
+ new_image_list_face = list(new_images_face)
+
+
cached_images = set(folder_embeddings.keys())
new_images = current_images - cached_images
deleted_images = cached_images - current_images
-
+
for img in deleted_images:
folder_embeddings.pop(img, None)
folder_paths.pop(img, None)
if not new_images: return [], []
new_image_list = list(new_images)
- ''' todo add back for faces
- self.process_faces(new_image_list)
- face_paths, face_embeddings = self.process_faces(new_image_list)
- for path, emb in zip(face_paths, face_embeddings):
- folder_embeddings_face[path] = emb
- folder_paths_face[path] = path
- save_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl", folder_embeddings_face, folder_paths_face)
- '''
+ if self.face:
+ face_paths, face_embeddings = self.process_faces(new_image_list_face)
+ for path, emb in zip(face_paths, face_embeddings):
+ folder_embeddings_face[path] = emb
+ folder_paths_face[path] = path
+ save_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl", folder_embeddings_face, folder_paths_face)
+ if not self.clip: return [], []
emb_ret = []
path_ret = []
for i in range(0, len(new_image_list), batch_size):
@@ -241,7 +256,7 @@ class CachedCLIPSearch:
def precompute_embedding_bs1_np(self, img): return precompute_embedding_jit_bs1(self.model, Tensor(img)).numpy() # todo remove
- def precompute_face_embedding_bs1_np(self, img): return adaface_jit(self.adaface, Tensor(img))[0].numpy() # todo remove
+ def precompute_face_embedding_bs1_np(self, img): return adaface_jit(self.adaface, Tensor(img)).numpy() # todo remove
def preprocess_clip(self, img):
if type(img) == bytes:
@@ -263,41 +278,90 @@ class CachedCLIPSearch:
return img
def img_to_face(self, orig):
- h, w = orig.shape[:2]
- scale = 640 / max(h, w)
- resized = cv2.resize(orig, (int(w*scale), int(h*scale)))
- delta_w, delta_h = 640 - resized.shape[1], 640 - resized.shape[0]
- top, bottom = delta_h // 2, delta_h - (delta_h // 2)
- left, right = delta_w // 2, delta_w - (delta_w // 2)
- orig = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])
- detections = blazeface_jit(self.blazeface, Tensor(orig)).numpy()
- detections = detections[detections[:, 4] != 0]
- # one face per person for now
- if detections.shape[0] > 0:
- x1, y1, x2, y2 = detections[0][:4]
- if (x2 - x1) < 60: return # min size of 60 for now?
- # 1.5x bigger
- cx = (x1 + x2) / 2
- cy = (y1 + y2) / 2
- w = x2 - x1
- h = y2 - y1
- scale = 1.5
- new_w = w * scale
- new_h = h * scale
- new_x1 = int(cx - new_w / 2)
- new_y1 = int(cy - new_h / 2)
- new_x2 = int(cx + new_w / 2)
- new_y2 = int(cy + new_h / 2)
- H, W = orig.shape[:2]
- new_x1 = max(0, new_x1)
- new_y1 = max(0, new_y1)
- new_x2 = min(W, new_x2)
- new_y2 = min(H, new_y2)
-
- cropped = orig[int(new_x1):int(new_x2), int(new_y1):int(new_y2)]
- face_img = cv2.resize(cropped, (112, 112))
- face_img = cv2.cvtColor(face_img, cv2.COLOR_RGB2BGR)
- return face_img
+ h, w = orig.shape[:2]
+ scale = 640 / max(h, w)
+ resized = cv2.resize(orig, (int(w*scale), int(h*scale)))
+ delta_w, delta_h = 640 - resized.shape[1], 640 - resized.shape[0]
+ top, bottom = delta_h // 2, delta_h - (delta_h // 2)
+ left, right = delta_w // 2, delta_w - (delta_w // 2)
+ orig = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])
+ detections = blazeface_jit(self.blazeface, Tensor(orig)).numpy()
+ detections = detections[detections[:, 0] != 0]
+ # one face per person for now
+ if detections.shape[0] > 0:
+ y1, x1, y2, x2 = detections[0][:4]
+ left_eye = np.array([detections[0][4], detections[0][5]])
+ right_eye = np.array([detections[0][6], detections[0][7]])
+
+ if (x2 - x1) < 50: return None
+ TARGET_LEFT_EYE = np.array([38, 51])
+ TARGET_RIGHT_EYE = np.array([73, 51])
+
+ eye_center = (left_eye + right_eye) / 2
+ target_eye_distance = np.linalg.norm(TARGET_RIGHT_EYE - TARGET_LEFT_EYE)
+
+ angle_rad = np.arctan2(right_eye[1] - left_eye[1], right_eye[0] - left_eye[0])
+ angle = np.degrees(angle_rad)
+
+ face_width = x2 - x1
+ face_height = y2 - y1
+
+ crop_size = max(face_width, face_height) * 2.0
+
+ x1_crop = int(eye_center[0] - crop_size / 2)
+ y1_crop = int(eye_center[1] - crop_size / 2)
+ x2_crop = int(eye_center[0] + crop_size / 2)
+ y2_crop = int(eye_center[1] + crop_size / 2)
+
+ H, W = orig.shape[:2]
+ x1_crop = max(0, x1_crop)
+ y1_crop = max(0, y1_crop)
+ x2_crop = min(W, x2_crop)
+ y2_crop = min(H, y2_crop)
+
+ if x2_crop <= x1_crop or y2_crop <= y1_crop: return None
+
+ cropped = orig[y1_crop:y2_crop, x1_crop:x2_crop]
+ crop_h, crop_w = cropped.shape[:2]
+
+ if crop_h == 0 or crop_w == 0: return None
+
+ left_eye_crop = left_eye - np.array([x1_crop, y1_crop])
+ right_eye_crop = right_eye - np.array([x1_crop, y1_crop])
+
+ rot_mat = cv2.getRotationMatrix2D((crop_w/2, crop_h/2), angle, 1.0)
+
+ cos_a = np.abs(rot_mat[0, 0])
+ sin_a = np.abs(rot_mat[0, 1])
+ new_w = int(crop_h * sin_a + crop_w * cos_a)
+ new_h = int(crop_h * cos_a + crop_w * sin_a)
+
+ rot_mat[0, 2] += (new_w / 2) - crop_w / 2
+ rot_mat[1, 2] += (new_h / 2) - crop_h / 2
+
+ rotated = cv2.warpAffine(cropped, rot_mat, (new_w, new_h))
+
+ left_eye_rot = rot_mat[:, :2] @ left_eye_crop + rot_mat[:, 2]
+ right_eye_rot = rot_mat[:, :2] @ right_eye_crop + rot_mat[:, 2]
+
+ rot_eye_distance = np.linalg.norm(right_eye_rot - left_eye_rot)
+ final_scale = target_eye_distance / rot_eye_distance
+
+ tx = TARGET_LEFT_EYE[0] - left_eye_rot[0] * final_scale
+ ty = TARGET_LEFT_EYE[1] - left_eye_rot[1] * final_scale
+
+ transform_mat = np.array([[final_scale, 0, tx], [0, final_scale, ty]], dtype=np.float32)
+
+ face_img = cv2.warpAffine(rotated, transform_mat, (112, 112))
+
+ face_img = cv2.cvtColor(face_img, cv2.COLOR_RGB2BGR)
+ # Debug draw dots for the eyes at target positions
+ #cv2.circle(face_img, (38, 51), 2, (0, 255, 0), -1)
+ #cv2.circle(face_img, (73, 51), 2, (0, 255, 0), -1)
+
+ return face_img
+
+ return None
def process_faces(self, paths):
ret_paths = []
@@ -307,9 +371,12 @@ class CachedCLIPSearch:
orig = cv2.imread(path)
orig = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
face_img = self.img_to_face(orig)
- if face_img is None: continue
+ if face_img is None:
+ ret_embeddings.append(None) # todo hack for now
+ ret_paths.append(path)
+ continue
cv2.imwrite(path.replace("objects","faces"), face_img)
- embeddings = adaface_jit(self.adaface, Tensor(face_img))[0].numpy()
+ embeddings = adaface_jit(self.adaface, Tensor(face_img)).numpy()
ret_embeddings.append(embeddings)
ret_paths.append(path)
@@ -325,6 +392,7 @@ class CachedCLIPSearch:
text_embedding = text_embedding.numpy()
all_similarities = []
for path, img_embedding in embeddings.items():
+ if img_embedding is None: continue
normalized_path = path.replace("\\", "/")
if cam_name and f"/cameras/{cam_name}/" not in normalized_path:
continue
diff --git a/test/test_clip.py b/test/test_clip.py
index 18031cc..7680910 100644
--- a/test/test_clip.py
+++ b/test/test_clip.py
@@ -1,14 +1,14 @@
-from clip import CachedCLIPSearch as CachedCLIPSearch
+from objects import ObjectFinder
import numpy as np
import os
def setup_clip_test():
if os.path.exists("test/clip_images/embeddings.pkl"): os.remove("test/clip_images/embeddings.pkl")
- clip = CachedCLIPSearch(prewarm=False)
+ clip = ObjectFinder(prewarm=False)
clip.precompute_embeddings("test/clip_images")
def test_clip_search():
- clip = CachedCLIPSearch()
+ clip = ObjectFinder()
clip._load_single_embeddings_file("test/clip_images/embeddings.pkl")
res = clip.search("ferrari f40")
np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)
@@ -22,7 +22,7 @@ def test_clip_search():
assert res[0][0] == "test/clip_images/micra.jpg"
def test_clip_search_jit():
- clip = CachedCLIPSearch()
+ clip = ObjectFinder()
clip._load_single_embeddings_file("test/clip_images/embeddings.pkl")
for _ in range(5): res = clip.search("ferrari f40")
np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)