class InvaderDetectorWithFace: def __init__(self): self.face_finder = FaceFinder() self.recognizer = FaceRecognizer() self.recognizer.load('trainer.yml') self.security_trigger = Trigger(20, lambda similarity: similarity > 80) def on_enabled_start(self): pass def on_disabled_update(self): pass def detect(self, frame): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = self.face_finder.find(gray) best_face = None best_confidence = 1000 for coordinates in faces: region_of_interest = get_region_of_interest(gray, coordinates) id_, conf = self.recognizer.predict(region_of_interest) if conf < best_confidence: best_face = region_of_interest best_confidence = conf print('{}, {}, {}'.format(datetime.now(), id_, conf)) # save_region_of_interest(gray, coordinates) self.highlight_face(frame, coordinates) if best_face is not None: if self.security_trigger.update(best_confidence): print('Face not match!') return True return False def highlight_face(self, image, coordinates, color=(0, 0, 255)): x, y, w, h = coordinates x_end = x + w y_end = y + h stroke = 2 cv2.rectangle(image, (x, y), (x_end, y_end), color, stroke)
import cv2 import os from face_finder import FaceFinder, get_region_of_interest from face_recognizer import FaceRecognizer from image_saver import ImageSaver test_dir = os.path.join('dataset', 'test') face_finder = FaceFinder() recognizer = FaceRecognizer() recognizer.load('trainer.yml') for file in os.listdir(test_dir): if file.endswith('png') or file.endswith('jpg'): filepath = os.path.join(test_dir, file) image_array = cv2.imread(filepath) image_array = cv2.cvtColor(image_array, cv2.COLOR_BGR2GRAY) faces = face_finder.find(image_array) for coordinates in faces: region_of_interest = get_region_of_interest( image_array, coordinates) predicted_label, confidence = recognizer.predict( region_of_interest) print('{}: {}, {}'.format(file, predicted_label, confidence))