Python OpenCV error with CascadeClassifier - python

import cv2
import imageio
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
def detect(frame):
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)
gray_face = gray[y:y+h, x:x+w]
color_face = frame[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(gray_face, 1.1, 3)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(color_face, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return frame
reader = imageio.get_reader('1.mp4')
fps = reader.get_meta_data()['fps']
writer = imageio.get_writer('output.mp4', fps=fps)
for i, frame in enumerate(reader):
frame = detect(frame)
writer.append_data(frame)
print(i)
writer.close()
the error I received is this;
Traceback (most recent call last):
File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 23, in <module>
frame = detect(frame)
File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 9, in detect
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

xml files are not in current folder but in some folder of cv2 module and you have to use full path to load them.
Lucky there is special variabel with folder name - cv2.data.haarcascades
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
To make sure you can use os.path.join() instead of +
face_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml'))
eye_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_eye.xml'))
If xml files are loaded then this should gives False
print(face_cascade.empty())
print(eye_cascade.empty())

Related

opencv in python showing a error not read video frame

read videocapture frame using cv2 but any time showing a error
error is :
Traceback (most recent call last):
File "d:\pythonprojects\gym\demo.py", line 33, in <module>
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
code is
<import cv2
import numpy as np
import os
from PIL import Image
from Attendance import attendance
from datetime import datetime
from database import\*
def getProfile(Id):
query="SELECT \* FROM users WHERE id="+str(Id)
cursor=mycursor.execute(query)
profile = mycursor.fetchone()
\# profile=None
\# for row in cursor:
\# profile=row
\# con.close()
return profile
\# os.chdir(os.getcwd())
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("face-trainner.yml")
cap = cv2.VideoCapture(0) #Get vidoe feed from the Camera
cap.set(3, 640)
cap.set(4, 480)
font = cv2.FONT_HERSHEY_COMPLEX
while(True):
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
nbr_predicted, conf = recognizer.predict(gray[y:y+h, x:x+w])
print(nbr_predicted, conf)
if(conf < 80):
profile=getProfile(nbr_predicted)
if profile != None:
time_now=datetime.now()
newdate=time_now.strftime('%Y-%m-%d')
newtime=time_now.strftime('%H:%M:%S')
attendance(nbr_predicted,newtime,newdate)
cv2.putText(img, "Name: "+str(profile[4]), (x, y+h+30), font, 0.4, (0, 0, 255), 1)
cv2.putText(img, "Gender: " + str(profile[7]), (x, y + h + 50), font, 0.4, (0, 0, 255), 1)
else:
cv2.putText(img, "Name: Unknown", (x, y + h + 30), font, 0.4, (0, 0, 255), 1)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('Preview',img) #Display the Video
cv2.waitKey(1)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This error seems to be due to img variable being None or empty. Not sure why it is None in your case. It could be due to various reasons like if the camera is not connected properly, or the camera driver is not installed, or there are permission issues.
You can add a condition after cap.read() call:
...
while True:
ret, img = cap.read()
if img is None:
print("Could not read frame from the source.")
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
...

AttributeError: module 'cv2' has no attribute 'CascadeClassifier'

im using cv2 to try to take a picture here is my code
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
eye_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
for (x, y, w, h) in faces:
#print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
img_item = "my-image.png"
cv2.imwrite(img_item, roi_color)
stroke = 2
color = (0, 255, 0)
end_cord_x = x + w
end_cord_y = y + h
ecolor = (50, 50, 50)
cv2.rectangle(frame, (x,y), (end_cord_x, end_cord_y), color, stroke)
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex,ey), (ex+ew,ey+eh), ecolor, 1)
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
i get the error:
File "c:NothereForPrivacyReasons\imagerecognition\face\picture.py", line 3, in
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
AttributeError: module 'cv2' has no attribute 'CascadeClassifier'

i am getting an error in my face recognition code while excuting it in pycharm, have also tried executing it on terminal

My face recognition code is getting and error. The error is as follows:
Traceback (most recent call last):
File "C:/Users/Harsh/Desktop/python codes/main.py", line 19, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-xeqjxthj\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-xeqjxthj\opencv\modules\videoio\src\cap_msmf.cpp (434) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
the code is as follows:
import cv2
face_cascade = \
cv2.CascadeClassifier('/C:/User/Harsh/Downloads/haarcascade_frontalface_alt.xml')
eye_cascade = \
cv2.CascadeClassifier('/C:/User/Harsh/Downloads/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
if ret is True:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
continue
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+h]
roi_color = img[y:y+h, x:x+h]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew), (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()
That error means that your xml file could not be found.
You got some typos here:
face_cascade =
cv2.CascadeClassifier('/C:/User/Harsh/Downloads/haarcascade_frontalface_alt.xml')
eye_cascade =
cv2.CascadeClassifier('/C:/User/Harsh/Downloads/haarcascade_eye.xml')
Notice the slash (/) at the beginning of the path. Correct that and it should work.

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

Unable to detect face and eye with OpenCV in Python

This code is to detect face and eyes using webcam but getting this error
Traceback (most recent call last):
File "D:/Acads/7.1 Sem/BTP/FaceDetect-master/6.py", line 28, in <module>
eyes = eyeCascade.detectMultiScale(roi)
NameError: name 'roi' is not defined
but when i use this code do detect faces and eyes in a image its working properly without any error
import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
faces = faceCascade.detectMultiScale(frame)
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]
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I think it is just a problem of indentation.
roi is out of scope when you go out of the faces loop.
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]
# eyes detection runs for each face
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)

Categories