Skip to content

Instantly share code, notes, and snippets.

@machinelearning147
Last active November 7, 2018 15:36
Show Gist options
  • Save machinelearning147/60bf8d9cd44b2ed0acd9fc9f21c44ec1 to your computer and use it in GitHub Desktop.
Save machinelearning147/60bf8d9cd44b2ed0acd9fc9f21c44ec1 to your computer and use it in GitHub Desktop.
import cv2
import matplotlib.pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
webcam=cv2.VideoCapture(1)
cv2.namedWindow("faceWindow", cv2.WINDOW_GUI_NORMAL)
PADDING = 10
try:
while webcam.isOpened():
_,frame = webcam.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.4, 5)
print(faces)
for (x, y, w, h) in faces:
x1 = x-PADDING
y1 = y-PADDING
x2 = x+w+PADDING
y2 = y+h+PADDING
frame = cv2.rectangle(frame,(x1, y1),(x2, y2),(255,0,0),3)
cv2.imshow('FaceWindow', frame)
if cv2.waitKey(20)&0xFF==27:
break
except KeyboardInterrupt:
print("Interrupted")
finally:
webcam.release()
cv2.destroyAllWindows()
## OR ##
video_capture = cv2.VideoCapture(1)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment