|
| 1 | +import face_recognition as fr |
| 2 | +import os |
| 3 | +import cv2 |
| 4 | +import numpy as np |
| 5 | +import time |
| 6 | +from VideoCapture import Device |
| 7 | + |
| 8 | + |
| 9 | +def get_encoded_faces(): |
| 10 | + |
| 11 | + encoded = {} |
| 12 | + |
| 13 | + for dirpath, dnames, fnames in os.walk("./faces"): |
| 14 | + for f in fnames: |
| 15 | + if f.endswith(".jpg") or f.endswith(".png"): |
| 16 | + face = fr.load_image_file("faces/" + f) |
| 17 | + encoding = fr.face_encodings(face)[0] |
| 18 | + encoded[f.split(".")[0]] = encoding |
| 19 | + |
| 20 | + return encoded |
| 21 | + |
| 22 | + |
| 23 | +def unknown_image_encoded(img): |
| 24 | + |
| 25 | + face = fr.load_image_file("faces/" + img) |
| 26 | + encoding = fr.face_encodings(face)[0] |
| 27 | + |
| 28 | + return encoding |
| 29 | + |
| 30 | + |
| 31 | +def classify_face(im): |
| 32 | + |
| 33 | + faces = get_encoded_faces() |
| 34 | + faces_encoded = list(faces.values()) |
| 35 | + known_face_names = list(faces.keys()) |
| 36 | + cam = Device() |
| 37 | + cam.saveSnapshot('~/faces/image.jpg') |
| 38 | + time.sleep(5) |
| 39 | + img = cv2.imread(im, 1) |
| 40 | + # img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5) |
| 41 | + # img = img[:,:,::-1] |
| 42 | + |
| 43 | + face_locations = fr.face_locations(img) |
| 44 | + unknown_face_encodings = fr.face_encodings(img, face_locations) |
| 45 | + |
| 46 | + face_names = [] |
| 47 | + for face_encoding in unknown_face_encodings: |
| 48 | + # See if the face is a match for the known face(s) |
| 49 | + matches = fr.compare_faces(faces_encoded, face_encoding) |
| 50 | + name = "Unknown" |
| 51 | + |
| 52 | + # use the known face with the smallest distance to the new face |
| 53 | + face_distances = fr.face_distance(faces_encoded, face_encoding) |
| 54 | + best_match_index = np.argmin(face_distances) |
| 55 | + if matches[best_match_index]: |
| 56 | + name = known_face_names[best_match_index] |
| 57 | + |
| 58 | + face_names.append(name) |
| 59 | + |
| 60 | + for (top, right, bottom, left), name in zip(face_locations, face_names): |
| 61 | + # Draw a box around the face |
| 62 | + cv2.rectangle(img, (left - 20, top - 20), |
| 63 | + (right + 20, bottom + 20), (255, 0, 0), 2) |
| 64 | + |
| 65 | + # Draw a label with a name below the face |
| 66 | + cv2.rectangle(img, (left - 20, bottom - 15), |
| 67 | + (right + 20, bottom + 20), (255, 0, 0), cv2.FILLED) |
| 68 | + font = cv2.FONT_HERSHEY_DUPLEX |
| 69 | + cv2.putText(img, name, (left - 20, bottom + 15), |
| 70 | + font, 1.0, (255, 255, 255), 2) |
| 71 | + |
| 72 | + # Display the resulting image |
| 73 | + img1 = cv2.resize(img, (960, 540)) |
| 74 | + cv2.imshow('Result', img1) |
| 75 | + cv2.waitKey(0) |
| 76 | + return face_names |
| 77 | + |
| 78 | + |
| 79 | +print(classify_face("image.jpg")) |
0 commit comments