1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import cv2 import numpy as np import face_recognition
imgElon = face_recognition.load_image_file('img/11.jpg') imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB)
faceLoc = face_recognition.face_locations(imgElon)[0] encodeElon = face_recognition.face_encodings(imgElon)[0] cv2.rectangle(imgElon, (faceLoc[3], faceLoc[0]), (faceLoc[1], faceLoc[2]), (255, 0, 255), 2)
imgTest = face_recognition.load_image_file('img/22.jpg') imgTest = cv2.cvtColor(imgTest, cv2.COLOR_BGR2RGB)
faceLocTest = face_recognition.face_locations(imgTest)[0]
width = faceLocTest[1] - faceLocTest[3] height = faceLocTest[2] - faceLocTest[0]
expand_width = min(width, imgTest.shape[1] - faceLocTest[1]) expand_height = min(height, imgTest.shape[0] - faceLocTest[2])
top_left = (max(0, faceLocTest[3] - expand_width), max(0, faceLocTest[0] - expand_height)) bottom_right = (min(imgTest.shape[1], faceLocTest[1] + expand_width), min(imgTest.shape[0], faceLocTest[2] + expand_height))
encodeTest = face_recognition.face_encodings(imgTest)[0] cv2.rectangle(imgTest, top_left, bottom_right, (255, 0, 255), 2)
result = face_recognition.compare_faces([encodeElon], encodeTest) faceDis = face_recognition.face_distance([encodeElon], encodeTest) print(result, faceDis) cv2.putText(imgTest, f'{result}{round(faceDis[0], 2)}', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2) cv2.imshow('Elon Musk', imgElon) cv2.imshow('Elon Test', imgTest) key = cv2.waitKey(0) if key == 27: cv2.destroyAllWindows()
|