import cv2
import os
cascPath = './data/'
face_detector = cv2.CascadeClassifier(cascPath + 'haarcascade_frontalface_alt.xml')
cam = cv2.VideoCapture(0)
cam.set(3,640)
cam.set(4,480)
# For each person, enter one numeric face id
face_id = input('\n enter user id end press <return> ==> ')
print('\n [INFO] Initializing face capture. Look the camera and wait ...')
#Initialize individual face count
count = 0
def creat_dir(path):
#判断路径是否存在,返回True,或者False
is_exists = os.path.exists(path)
if is_exists:
print('The path is exist')
else:
os.makedirs(path)
print('Create the dir successfully.')
savepath = './face_dataset/'
dirpath = savepath + '{}/'.format(face_id)
creat_dir(dirpath)
while True:
ret,img = cam.read()
# frame = cv2.flip(frame,-1)#旋转屏幕
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
count += 1
# Save the captured image into the datasets folder
cv2.imwrite(dirpath + str(face_id) +'.' + str(count) + '.jpg', gray[y:y+h, x:x+w])
cv2.imshow('img',img)
k = cv2.waitKey(100) & 0xff
if k == 27: #press 'ESC' to quit
break
elif count >= 30: # Take 30 face sample and stop video
break
# Do a bit of cleanup
print('\n [INFO] Exiting Program and cleanup stuff')
cam.release()
cv2.destroyAllWindows()