#!/usr/bin/python3 """Record a Howdy face model from many frames, for howdy-settings. Howdy's own "add" keeps one frame. This records for a few seconds while the user turns their head and keeps the most different views, so the model covers more angles. Usage, as root: enroll.py USER LABEL """ import configparser import json import pathlib import sys import time import numpy as np HOWDY_DIRS = ["/usr/lib64/howdy", "/usr/lib/howdy"] SECONDS = 8 MIN_VIEWS = 5 def pick_diverse(views, count=8, spread=0.05): """Start from the most typical view, then add the view farthest from the chosen ones until there are `count` or the rest are closer than `spread`.""" views = np.array(views) distances = np.linalg.norm(views[:, None] - views[None, :], axis=2) chosen = [int(distances.sum(axis=1).argmin())] while len(chosen) < count: nearest = distances[:, chosen].min(axis=1) best = int(nearest.argmax()) if nearest[best] < spread: break chosen.append(best) return [views[i].tolist() for i in chosen] def record(config): import dlib # noqa: E402 dlib before OpenCV, as Howdy does import cv2 import paths_factory from recorders.video_capture import VideoCapture from rotation import rotate_frame detector = dlib.get_frontal_face_detector() pose = dlib.shape_predictor(paths_factory.shape_predictor_5_face_landmarks_path()) encoder = dlib.face_recognition_model_v1( paths_factory.dlib_face_recognition_resnet_model_v1_path()) dark_threshold = config.getfloat("video", "dark_threshold", fallback=60) rotate = config.getint("video", "rotate", fallback=0) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) capture = VideoCapture(config) views, frames, start = [], 0, time.monotonic() while time.monotonic() - start < SECONDS: frames += 1 frame, gsframe = capture.read_frame() gsframe = clahe.apply(gsframe) hist = cv2.calcHist([gsframe], [0], None, [8], [0, 256]) if hist.sum() == 0 or hist[0][0] / hist.sum() * 100 > dark_threshold: continue frame = rotate_frame(frame, rotate, frames) gsframe = rotate_frame(gsframe, rotate, frames) faces = detector(gsframe, 1) if len(faces) == 1: landmarks = pose(frame, faces[0]) views.append(list(encoder.compute_face_descriptor(frame, landmarks, 1))) capture.release() return views def main(user, label): sys.path[:0] = HOWDY_DIRS import paths_factory config = configparser.ConfigParser() config.read(paths_factory.config_file_path()) views = record(config) if len(views) < MIN_VIEWS: sys.exit("No face seen long enough, look at the camera and try again") model_file = pathlib.Path(paths_factory.user_model_path(user)) models = json.loads(model_file.read_text()) if model_file.exists() else [] models.append({ "time": int(time.time()), "label": label, "id": models[-1]["id"] + 1 if models else 0, "data": pick_diverse(views), }) model_file.write_text(json.dumps(models)) if __name__ == "__main__": main(*sys.argv[1:3])