Webcam face detection in python using Opencv- dimensions of single frames - python

I have been trying to run a face detection feature from my webcam using code from realpython.com and suggestions I saw on this site.
import cv2
import sys
import os
cascPath = "{base_path}/folder_with_your_xml/haarcascade_frontalface_default.xml".format(
base_path=os.path.abspath(os.path.dirname(__file__)))
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.cv.CV_HAAR_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)
# 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()
This is the error I get when I run the code:
File "videocam.py", line 16, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
From what I've gathered, it's because frame is not 3-dimensional and a NoneType object. I am only just starting with OpenCV and face recognition, so I'm not entirely sure how to fix this.

Related

assertion failed 215 error when trying to detect faces

I'm using OpenCV with Python to try to detect faces with multidetect but it seems to have a problem with it.
This is my code:
#import required libraries
import cv2
import time
#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
#start the camera
video_capture = cv2.VideoCapture(0)
#give camera time to warm up
time.sleep(0.1)
#start video frame capture loop
while True:
# take the frame, convert it to black and white, and look for facial features
faceCascade = cv2.CascadeClassifier(cascPath)
ret, frame = video_capture.read()
if not ret: break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# use appropriate flag based on version of OpenCV
if int(cv2.__version__.split('.')[0]) >= 3:
cv_flag = cv2.CASCADE_SCALE_IMAGE
else:
cv_flag = cv2.cv.CV_HAAR_SCALE_IMAGE
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv_flag
)
#for each face, draw a green rectangle around it and append to the image
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#display the resulting image
cv2.imshow('Video', frame)
#set "q" as the key to exit the program when pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# clear the stream capture
video_capture.release()
cv2.destroyAllWindows()
and this is the error I'm getting:
faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-_8k9tw8n\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
Solution:
The important part of your error is:
error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
Basically the problem is it can't find the file in the given directory or it could be a format problem. So, try to download the file again or use the file that comes with the opencv pip package like so:
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

<class 'cv2.CascadeClassifier'> returned a result with an error set

so, I'm trying to code face detection but its not working. this is my code:
import cv2
import sys
cascPath = sys.argv[0]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
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.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I'm very new to coding so I don't know if I'm missing something obvious
Change your code as follows:
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
This worked for me.

OpenCV Human Body Detection through a webcam - No detections visible

I am trying to detect the human body through OpenCV. The code throws no error. The camera also starts but it is unable to detect anything.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while (True):
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
#cv2.VideoCapture(0).release()
I highly suspect its an indentation error. The camera does start, but your code to draw the bounding boxes of the faces are outside of the loop. Just indent that code. In addition, you'll need to free the camera resource properly or the next time you run the code, the camera will not be able to capture frames properly. I've changed the release call so that it releases the grabbed resource.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while True:
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
video_captured.release() # Changed so that you're releasing the grabbed resource

Assertion fail with Open CV

I'm new to openCV and am trying to get openCV to work my USB webcam on Win7 with Python 3.8. I've got the basic tutorial from here modified from Raspberry Pi cam by the same author here.
which is:
#!/usr/bin/python3
import time
import numpy as np
import cv2
#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
#start the camera
video_capture = cv2.VideoCapture(0)
#give camera time to warm up
time.sleep(0.1)
#start video frame capture loop
while True:
# take the frame, convert it to black and white, and look for facial features
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# use appropriate flag based on version of OpenCV
if int(cv2.__version__.split('.')[0]) >= 3:
cv_flag = cv2.CASCADE_SCALE_IMAGE
else:
cv_flag = cv2.cv.CV_HAAR_SCALE_IMAGE
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv_flag
)
#for each face, draw a green rectangle around it and append to the image
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#display the resulting image
cv2.imshow('Video', frame)
#set "q" as the key to exit the program when pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# clear the stream capture
video_capture.release()
cv2.destroyAllWindows()
It should run out of the box, but I get the error below and I'm not sure why. CV_flag and gray have data and the other parameters are filled. Any ideas.
C:\Users\Ghoul>py D:\LearnPython\open_cv_face_track_test.py -3.8
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674)
SourceReaderCB::~SourceReaderCB
terminating async callback
Traceback (most recent call last):
File "D:\LearnPython\open_cv_face_track_test.py", line 31, in <module>
faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.1.2) C:\projects\opencv-
python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Ass
ertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
The faceCascade classifier is empty, which means it was unable to retrieve the classifier from the path provided.
You can replace the line
cascPath = "haarcascade.xml"
with:
cascPath = '../../haarcascade.xml'
where you provide the full path of the xml file for cascPath.

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.

Categories