Last active
April 24, 2019 17:19
-
-
Save jwalsh/980df35aefa15a07e4bd38f7a556667e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 | |
import time | |
import datetime | |
# import the cascade for face detection | |
face_cascade = cv2.CascadeClassifier("cascades/haarcascade_frontalface_default.xml") | |
def TakeSnapshotAndSave(): | |
# access the webcam (every webcam has a number, the default is 0) | |
cap = cv2.VideoCapture(0) | |
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) | |
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) | |
count = 0 | |
anterior = 0 | |
# while count < 100: | |
while(cap.isOpened()): | |
if count % 30 == 0: | |
print(count, datetime.datetime.now()) | |
# Capture frame-by-frame | |
ret, frame = cap.read() | |
# to detect faces in video | |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
faces = face_cascade.detectMultiScale(gray, 1.3, 5) | |
for (x, y, w, h) in faces: | |
print(x, y, w, h) | |
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) | |
if len(faces) > 0: | |
cv2.imwrite("opencv-" + str(time.time()) + ".jpg", frame) | |
# Create training data | |
for (x, y, w, h) in faces: | |
print("training-face-128", x, y, w, h) | |
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) | |
cropped = frame[y:y+h, x:x+w] | |
resized = cv2.resize(cropped, (128, 128), interpolation = cv2.INTER_AREA) | |
cv2.imwrite("training-face-128/opencv-" + str(time.time()) + ".jpg", resized) | |
if count % 100 == 0: | |
cv2.imwrite("debug-" + str(count) + ".jpg", frame) | |
if anterior != len(faces): | |
anterior = len(faces) | |
print("faces: " + str(len(faces)) + " at " + str(datetime.datetime.now())) | |
count = count + 1 | |
time.sleep(2) | |
cap.release() | |
if __name__ == "__main__": | |
TakeSnapshotAndSave() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment