Learn practical skills, build real-world projects, and advance your career
import glob
import face_recognition
import cv2
import numpy as np
import glob
import jovian

Pre processing, Face encoding and Training

paths = glob.glob('C:\\Users\\vsneh\\Udemy-notebooks\\Opencv_facebk_auto_uplod\\data\\*')
names = []
images = []
image_encodings = []
image_names = []
count_img = 0
for i in paths:
    images.append(face_recognition.load_image_file(i))
    image_encodings.append(face_recognition.face_encodings(images[count_img])[0])
    image_names.append(i.split('\\')[-1].split('.')[0])
    count_img+=1
    print(image_names)
['snehit2']

Face Detection

count = 0
cap = cv2.VideoCapture(0)
while True:
    ret,frame = cap.read()
    gray = frame[:, :, ::-1]
    face_locations = face_recognition.face_locations(gray)
    face_encodings = face_recognition.face_encodings(gray, face_locations)
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        matches = face_recognition.compare_faces(image_encodings, face_encoding)
        name = 'Unknown'
        
        face_distances = face_recognition.face_distance(image_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = image_names[best_match_index]
        if(name!='Unknown'):
            cv2.imwrite('C:\\Users\\vsneh\\Udemy-notebooks\\Opencv_facebk_auto_uplod\\collected_pics\\pic-{}.jpg'.format(count),frame)
            count+=1
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 1)
    cv2.imshow("output",frame)
    if(cv2.waitKey(1)==ord('q')):
        break
cap.release()
cv2.destroyAllWindows()