How to Extract Faces from a Video Using Haarcascade? - python

I am using below script for haarcascade face detection.
My aim is to collect face shots on a video.
I would like to extract faces from a video.
Below script provides the detection of faces on a video.
How could I extract detected faces on a video?
import numpy as np
import cv2
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()

Related

Cropping live video input from a webcam for facial identification

I am working with OpenCV in Python for facial identification and I want to crop the live video from my webcam to just output the face it recognizes.
I have tried using ROI but I do not know how to correctly implement it.
import cv2
import sys
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# 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)
roi = frame[y:y+h, x:x+w]
cropped = frame[roi]
# Display the resulting frame
cv2.imshow('Face', cropped)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
.
Traceback (most recent call last):
File "C:/Users/Ben/Desktop/facerecog/facerecog2.py", line 31, in <module>
cv2.imshow('Face', cropped)
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\array.cpp:2492: error: (-206:Bad flag (parameter or structure field)) Unrecognized or unsupported array type in function 'cvGetMat'
You get cropped image with
cropped = frame[y:y+h, x:x+w]
and then you can display it.
But sometimes there is no face on frame and it will not create cropped and you can get error. Better create this variabel before for and check it after for
cropped = None
for (x, y, w, h) in faces:
cropped = frame[y:y+h, x:x+w]
if cropped is not None:
cv2.imshow('Face', cropped)
#else:
# cv2.imshow('Face', frame)
or
if faces:
(x, y, w, h) = faces[0]
cropped = frame[y:y+h, x:x+w]
cv2.imshow('Face', cropped)
I don't know what you want to do if there will be many faces on frame.

Eyes recognition using Haar-classifier of a static photo

it is possible to use haarclassifier on a static photo instead of the live streaming of the webcam?
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
I need to recognize just one or all eyes of the photo, without face.
Any suggest?
I edit from ur code
import cv2
#load haarcascade_eye
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
# Load an color image
img = cv2.imread('Test_Image.jpg',cv2.IMREAD_COLOR)
#convert to gray scale to work with HAAR
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#read HAAR ade loop for find eye(s)
eyes = eye_cascade.detectMultiScale(gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)
#show eye(s) rectangle in color image
cv2.imshow('img',img)
#press any key to close
cv2.waitKey(0)
cv2.destroyAllWindows()

OpenCV 3.4.0.12 with Python3.5 AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'

I'm trying out facial recognition for the first time with python 3.5 and OpenCV 3.4.0.12 and I get this error when I run my code.
File "/Users/connorwoodford/anaconda3/envs/chatbot/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/connorwoodford/Desktop/temp.py", line 11, in <module>
ret, img = cap.imread()
AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'
Code:
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('CascadeClassifier')
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x,y,w,h) in faces:
cv2.rectangle(img, (x+y), (x+w, y+h), (255,0,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew,ey+eh), (0,255,0), 2)
cv2.imshow('img',img)
k = cv2.waitkey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Your eye_cascade is referring to wrong cascade file, it should end with .xml extension. You can download it from here haarcascade_eye.xml.
Also note that your call to cv2.rectangle is not in correct format.
change it from
cv2.rectangle(img, (x+y), (x+w, y+h), (255,0,0), 2)
to
cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
All you need to make this work is to wrap the capture logic in a method. Full code goes as follows:
import numpy as np
import cv2
def sample_demo():
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
and simply call method sample_demo()
sample_demo()

NameError in Python

I am getting a NameError: name 'eyes' not found while trying to run an OpenCV project in Python on cmd. I am using Python 2.7 and OpenCV 2.4.13, which I think is not a problem.
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(1)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x,y,w,h) in faces:
cv2.reactangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for(ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew,ey+eh), (0,255,0), 2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Error:
File "detect.py" , line 19, in
for(ex,ey,ew,eh) in eyes:
NameError: name 'eyes' is not defined
Problem of indentation, just like this one:
eyes is out of scope when you go out of the faces loop.
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x,y,w,h) in faces:
cv2.reactangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
# this one should be inside the 'faces' loop
for(ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew,ey+eh), (0,255,0), 2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break

OpenCV 3.0 Beta - Python - Face Detection via Webcam - code gives me error

I wrote and looked over this code multiple times and it seems right to me especially that it's very simple and straight forward (Took snippet out of opencv tutorial), however it is still giving me an error. I've checked the error and I understand that it's missing channels, however, I don't know how to fix it. Any help would be appreciated. I'm using Windows x64 and Spyder (from Anaconda distribution) as my IDE. Could it be hardware issue? (webcam)
#####################################################
# Face Detection (Video) #
#####################################################
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
video = cv2.VideoCapture(0)
ret, frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
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]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
Here's the error I get:
error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:5731:
error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
i guess, you wanted a 'continuous detection, not a 'single shot' one, right ?
you're just some small changes away:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
if face_cascade.empty(): raise Exception("your face_cascade is empty. are you sure, the path is correct ?")
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
if eye_cascade.empty(): raise Exception("your eye_cascade is empty. are you sure, the path is correct ?")
video = cv2.VideoCapture(0)
while(video.isOpened()):
ret, frame = video.read()
if frame not None:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
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]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()

Categories