import numpy as np
import cv2
#initilize cam
cap = cv2.VideoCapture(0)
#face detection
face_cascade = cv2.CascadeClassifier(“haarcascade_frontalface_alt.xml”)
skip = 0
face_data =[]
dataset_path= ‘./data/’
file_name =input("Enter the name of the person: ")
while (True):
# Capture frame-by-frame
ret,frame = cap.read()
if ret == False:
continue
gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(frame,1.3,5)
faces = sorted(faces,key=lambda f:f[2]*f[3])
#pick the last face coz its the largert face according to sorted list of faces
for face in faces[-1:]:
x,y,w,h = face
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),2)
#extract the crop out face
offset = 10
face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
face_section = cv2.resize(face_section,(100,100))
skip += 1
if skip%10==0:
face_data.append(face_section)
print(len(face_data))
cv2.imshow("frame",frame)
cv2.imshow("Face Section",face_section)
# Display the resulting frame
cv2.imshow('video_frame',frame)
if cv2.waitKey(1)&0xff == ord('q'):
break
#convert face list array into numpy array
face_data = np.asarray(face_data)
face_data = face_data.reshape((face_data.shape[0],-1))
print(face_data.shape)
#save this data into file sys
np.save(dataset_path+file_name+’.npy’,face_data)
print(“data succesfully saved”)
When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
indent preformatted text by 4 spaces