Skip to content

Instantly share code, notes, and snippets.

@dokeeffe
Created July 12, 2018 07:35
Show Gist options
  • Save dokeeffe/44ad0d2497452fb9bcffeb94152d00ab to your computer and use it in GitHub Desktop.
Save dokeeffe/44ad0d2497452fb9bcffeb94152d00ab to your computer and use it in GitHub Desktop.
Capture and save faces from a webcam
import cv2, time
cap = cv2.VideoCapture(0)
cap.set(3, 640) #WIDTH
cap.set(4, 480) #HEIGHT
face_cascade = cv2.CascadeClassifier('/home/okeefd3/.local/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
face_counter = 0
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
print(len(faces))
crop_img = frame[y:y+h, x:x+w]
cv2.imwrite('/home/okeefd3/Desktop/faces/face{}.jpeg'.format(face_counter),crop_img)
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
face_counter+=1
cv2.imshow('frame',frame)
time.sleep(0.1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment