def show(args): with fc.util.Camera() as cam: # load recognizer, archive and start camera and window detector = fc.FaceDetector() recognizer = fc.FaceRecognizer() dataset = pickle.load(args["EMBED_FILE"]) with fc.util.ImageWindow("camera") as window: while True: # load image from webcam frame = cam.image() if frame is None: print("end of streaming") break # find faces, and who they are faces, boxes = detector.crop_aligned_faces(frame, (112, 112), with_boxes=True) if len(faces) != 0: found_names = recognizer.assign_names(dataset, faces) found_names = [ "{} ({:.2f} %)".format(name, conf * 100) for name, conf in found_names ] window.show(frame, box_faces=(boxes, found_names)) else: window.show(frame) # check for end if cv2.waitKey(1) & 0xFF == ord("q"): break
def _load_from_video(video_path): detector = fc.FaceDetector() faces_to_return = [] cap = cv2.VideoCapture(video_path) frame_rate = cap.get(5) ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) i = 0 while ret is True: if i % frame_rate == 0: faces = detector.crop_aligned_faces(frame, resize=(112, 112)) if len(faces) == 1: faces_to_return.append(faces[0]) ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) else: ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) else: ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) i += 1 cap.release() return faces_to_return
def load_faces(folder: str) -> Dict[str, ndarray]: """ Search for faces in files of type jpg, png and mp4 inside `folder` path. Images or frames of videos with none or more than one face are skipped. To each recognized face is assigned a name equal to the name of the file until '-' character. For instance a file named 'andreaconti-1.jpg' will led to 'andreaconti' label. If a video is found, frames are sampled at 1s distance. Parameters ---------- folder : str path of the folder in which search for faces Returns ------- array_like, array_like tuple containing a list of faces and the list of matching labels """ detector = fc.FaceDetector() result: Dict[str, ndarray] = {} for f_name in os.listdir(folder): # assigned name name = os.path.basename(f_name) name = os.path.splitext(name)[0] name = name.split("-")[0] # load face from image if f_name.lower().endswith((".jpg", ".png")): img = cv2.cvtColor(cv2.imread(os.path.join(folder, f_name)), cv2.COLOR_BGR2RGB) faces = detector.crop_aligned_faces(img, resize=(112, 112)) if len(faces) == 0: print(f"[WARNING] face not found in {f_name}, skipped.") continue if len(faces) > 1: print(f"[WARNING] too many faces found in {f_name}, skipped.") continue if name not in result.keys(): result[name] = [] face = faces[0] result[name].append(face) # load face from video elif f_name.lower().endswith(".mp4"): faces = _load_from_video(os.path.join(folder, f_name)) if name not in result.keys(): result[name] = [] face = faces[0] result[name].extend(faces) for k in result.keys(): result[k] = np.stack(result[k]) return result
def recognize(args): detector = fc.FaceDetector() embedder = fc.FaceEmbedder() recognizer = pickle.load(args["EMBED_FILE"]) img = cv2.imread(args["IMG"]) cv2.cvtColor(img, cv2.COLOR_BGR2RGB) faces = detector.crop_aligned_faces(img, resize=(112, 112)) faces_embedded = embedder.embed_faces(faces) names = recognizer.assign_names(faces_embedded) for name in names: print(f"found: {name}")
def test_face_embedding(): # load img img = cv2.imread(file_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # find faces face_detector = fc.FaceDetector() faces = face_detector.crop_aligned_faces(img, resize=(112, 112)) assert faces.shape[0] == 1 # embed embedder = fc.FaceRecognizer() faces_emb = embedder.embed_faces(faces) assert faces_emb.shape == (1, 128)
def watch(self, dataset: Dict[str, ndarray]): detector = fc.FaceDetector() recognizer = fc.FaceRecognizer() with Camera() as cam: while True: frame = cam.image() if frame is None: return # find faces, and who they are faces = detector.crop_aligned_faces(frame, (112, 112)) if len(faces) != 0: found_names = recognizer.assign_names(dataset, faces) # call registered functions for name, _ in found_names: if name in self._handlers: for fn in self._handlers[name]: fn()
""" Test of simple face detection """ from face_recognition_cam import __version__ import face_recognition_cam as fc import cv2 import os def test_version(): assert __version__ == '0.1.0' file_path = os.path.join(os.path.dirname(__file__), 'test_data', 'sample.jpg') face_detector = fc.FaceDetector() def test_face_detection(): # load img img = cv2.imread(file_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # find faces boxes = face_detector.find_face_boxes(img) assert boxes.shape[0] == 1 def test_face_embedding():