cv2 : cv2Color() - python

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

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')

OpenCV(4.4.0) error: (-215:Assertion failed) isMap() in function 'cv::FileNode::operator []'

I am working on a facial detector script.
I have managed to create a dataset by capturing images from a webcam, saving them to a local directory and storing the data on my local database.
but when I try to run the main app to recognize the faces and display them to me, I am getting the following error:
runfile('C:/Users/JeanCamargo/Google Drive/python/college/face recognition/face recognition.py', wdir='C:/Users/JeanCamargo/Google Drive/python/college/face recognition')
Reloaded modules: dbconnect
Traceback (most recent call last):
File "C:\Users\JeanCamargo\Google Drive\python\college\face recognition\face recognition.py", line 27, in <module>
recognizer.read(r"trainner\trainningData.yml")
error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-6lylwdcz\opencv\modules\core\src\persistence.cpp:2089: error: (-215:Assertion failed) isMap() in function 'cv::FileNode::operator []'
Any ideas on what's causing this? the file I am running goes as following.
import cv2
import sys
import numpy as np
import pickle
from PIL import Image
from dbconnect import mySQL
import os
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read(r"trainner\trainningData.yml")
cascPath = r"Classifiers\haarcascade_frontalface_alt.XML"
faceCascade = cv2.CascadeClassifier(cascPath)
#Id = 0
path = 'dataSet'
def getProfile(Id):
query = "SELECT * FROM people WHERE ID ="+ Id
cursor = query.fetchall()
mySQL.close()
profile = None
for row in cursor:
profile = row
return profile
video_capture = cv2.VideoCapture(1)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1,.5,0,2,1)
profiles={}
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
if ret==False:
continue
frame = cv2.flip(frame, 1) # Flip image
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
profile = getProfile(id)
if (profile !=None):
cv2.cv.PutText(cv2.cv.fromarray(frame),profile[1],(x,y+h+30),255)
cv2.cv.PutText(cv2.cv.fromarray(frame),profile[2],(x,y+h+60),255)
cv2.cv.PutText(cv2.cv.fromarray(frame),profile[3],(x,y+h+90),255)
cv2.cv.PutText(cv2.cv.fromarray(frame),profile[4],(x,y+h+120),255)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
I eventually found an answer to this.
this is happening due to:
cv2.face.LBPHFaceRecognizer_create()
This is the correct invocation for OpenCV. but most likely, you do not have the face submodule, because your cv2.pyd was built without opencv_contrib
there's a couple of options:
rebuild from src with opencv_contrib, you need a c++ compiler and CMake for this.
fall back to opencv2.4 and use
cv2.createLBPHFaceRecognizer()
once this is done and train the data again it will work ok

cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception

I was browsing StackOverflow, and of course I found a similar post about the problem!
"cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception"
However, as it has been 5 months with no answers on that, I've opened a new thread. Here it goes!
I've got an error when I try to run cv2.VideoCapture(url).
The box is running openCV 4.4, Centos 7, Raspberry PI 4, ARMV7L. See source and logs bellow.
I believe it's related to NumPy library, however, I'm still debugging it.
Does anyone has experienced the same? Any ideas on how to solve it?
Please see the source and log messages bellow.
Best wishes,
I
import numpy as np
import cv2
import sys
import random, string
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
url = 'rtsp://<ip-direction:port/path>'
print("Running py script detectFacesEyes.py")
video_capture = cv2.VideoCapture(url)
print(video_capture)
while True:
ret, img = video_capture.read()
print(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3,
minSize=(30, 30))
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 = eyeCascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0), 2)
if len(eyes) != 0:
crop_img = img[y-99:y+h+99, x-36:x+w+36]
if len(crop_img) != 0:
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(12))
status = cv2.imwrite(result_str+".jpg", crop_img)
#This breaks on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
python detectFacesEyes.py
Running py script detectFacesEyes.py
[ERROR:0] global /usr/local/src/opencv_build/opencv/modules/videoio/src/cap.cpp (142) open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.4.0-dev) /usr/local/src/opencv_build/opencv/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): rtsp://ip-direction:port/path in function 'icvExtractPattern'
<VideoCapture 0xb196d710>
None
Traceback (most recent call last):
File "detectFacesEyes.py", line 19, in
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0-dev) /usr/local/src/opencv_build/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

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.

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

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.

Categories