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')
Related
I'm trying to do a face recognition that can detect faces and for some weird reason my code is giving me error
the error :
line 13, in <module>
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-
m8us58q4\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in
function 'cv::cvtColor'
the code itself:
import numpy as np
import cv2
faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
while True:
ret , img = cap.read()
img = cv2.flip(img,-1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize = (20,20)
)
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]
cv2.imshow('video',img)
k = cv2.waitKey(30) & 0xff
if k == 27: # pressing esc in order to quit
break
cap.release()
cap.destroyAllWindows()
I would be very happy if some of the people who may read this will send me their solution by the way I'm very sorry about my indentation I'm just kinda new to stack overflow
It seems like your VideoCapture() did not grab frames.
Try to check the script on a saved video first (VideoCapture("vid_name.mp4")).
Try disabling the cv2.flip() and see if it helps, if yes, perhaps try move this flipping to after converting the source frame to gray.
Also it is a good idea to check the value of ret in ret, frame = cap.read() by using
if not ret:
print('no frame')
break
Then if the program exits with this error message, it means there's something wrong with the camera connection.
Modifying code like this worked for me. Putting the frame part outside the loop and then continuing:
import numpy as np
import cv2
faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
ret , img = cap.read()
img = cv2.flip(img,-1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
while True:
if ret == False:
continue
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize = (20,20)
)
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]
cv2.imshow('video',img)
k = cv2.waitKey(30) & 0xff
if k == 27: # pressing esc in order to quit
break
cap.release()
cap.destroyAllWindows()
With regard to the error message you posted: The issue is the the HaarCascade classifer did not properly load due to the syntax in the load command. I was able to get it to work by
making sure I hade the file: https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
placing it into a known directory and modifying the load command to match.
...
import numpy as np
import cv2
faceCascade = cv2.CascadeClassifier('c:\\Cascades\\haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
ret , img = cap.read()
img = cv2.flip(img,-1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
while True:
if ret == False:
continue
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize = (20,20))
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]
cv2.imshow('video',img)
k = cv2.waitKey(30) & 0xff
if k == 27: # pressing esc in order to quit
break
cap.release()
cap.destroyAllWindows()
I'm trying to do face detect someone
import cv2
import sys
faceCascade = cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")
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),
# cv2.CASCADE_SCALE_IMAGE
flags=cv2.CASCADE_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()
but everytime I run the program I get this error:
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-pz4stnv8\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
and there is not a appveyor folder in Users even if I show hidden items so I can't reach it.
video_capture.read() is not guaranteed to return a valid frame.
ret is either True or False depending on whether a frame was read successfully. You should check this value before attempting to further process the frame -- e.g. by adding:
if not ret:
continue
The path in the error message is the path to the source code on the machine that was used to build OpenCV, so isn't necessarily the a real path on your machine. That is nothing to worry about.
thankss but now ı got this error:
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build- zsozjuva\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-zsozjuva\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
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.
I am using a Raspberry Pi 3 Model B, with Raspbian, opencv 2.x and Python 3 installed.
I want to access my USB Webcam and take a picture with it. I've found tons of code but none are of any use. I found one which is better but when I run the command
cascPath = sys.argv[1]
I get the error
Traceback (most recent call last):
File "/home/pi/test.py", line 4, in
cascPath = sys.argv[1]
IndexError: list index out of range
I simply need to access my webcam to take a picture.
I am using the following code :
import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
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()
This code try to recognize faces on image and sys.argv[1] expects you run script with path to XML file which help recognize faces.
If you don't want to recognize faces then you need only this code to display on monitor video from camera.
import cv2
import sys
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
# Display the resulting frame
cv2.imshow('Video', frame)
# exit if you press key `q`
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
video_capture.release()
Or this to save image
import cv2
video_capture = cv2.VideoCapture(0)
# Capture frame
ret, frame = video_capture.read()
# Write frame in file
cv2.imwrite('image.jpg', frame)
# When everything is done, release the capture
video_capture.release()
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.