python3 opencv error, how i can fix that? [duplicate] - python

I'm trying to learn cv2 in python 2.7, but when I run my code, in the specific part of it:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
it returns this:
File "face_detection.py", line 11, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/objdetect/src/cascadedetect.cpp:1595: error: (-215) !empty() in function detectMultiScale
I tried to search the answer here but the best i could find is that I must be loading the face_cascade the wrong way... Any help?

I had the same issue.
I didn't need to download anything else to solve this. CV2 had everything I needed.
Instead of trying to figure out where the .xml files are and hard coding the values, I used a property given by cv2.
From OP
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Becomes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

The XML or file is missing or the path to it is incorrect or the create_capture path is incorrect.
The paths in the opencv sample look like this:
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')

I ran the same code. There are two things to note here.
1. Give the entire path of the .xml files.
2. Give a key press event instruction at the end.
Add this block of code at the end and run your file, worked for me:
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
For example, my code looked like
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)
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(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
My output looked like this:

You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

The XML file is missing, you can get the file from the GitHub repository and place it in the same directory as your project. Link to the folder on GitHub is here. Just download the file named haarcascade_frontalface_default.xml.
Actually, the file exists on your system. Just go to the site-packages folder of your python installation folder and check the cv2/data folder for the file

Use the entire file path and use "\\" instead of "\" in the xml file path.
The file path should be as follows:
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
instead of:
cascade_fn = args.get('--cascade', "..\..\data\haarcascades\haarcascade_frontalface_alt.xml")

no need to change the code
download that .xml file , then put the path of that file
it will solve the error (100%)

If you are using Anaconda you should add the Anaconda path.
new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'
face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')

This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.
You can use the built-in pkg_resources module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2 module was loaded from:
import pkg_resources
haar_xml = pkg_resources.resource_filename(
'cv2', 'data/haarcascade_frontalface_default.xml')
For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'; yours is guaranteed to be different. Just let python’s pkg_resources library figure it out.
classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)
Success!

On OSX with a homebrew install the full path to the opencv folder should work:
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')
Take care of the version number in the path.

Probably the face_cascade is empty. You can check if the variable is empty or not by typing following command:
face_cascade.empty()
If it is empty you will get True and this means your file is not available in the path you mentioned.
Try to add complete path of xml file as follows:
r'D:\folder Name\haarcascade_frontalface_default.xml'

"\Anaconda3\Lib\site-packages\cv2\data\" I found the xml file in this path for Anaconda

You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example
This will not work
front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Use full path, now it will work fine
front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')

I found this in some other answer but eventually worked for me when I added the two answers.
import cv2
from matplotlib import pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
img = cv2.imread('image1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

You may find such kind of errors when you did not define the complete path of your XML file.
Try this one if you are using opencv3.1.0 in raspberrypi 3:
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')

Your XML file was not found. Try using absolute paths like:
/path/to/my/file (Mac, Linux)
C:\\path\\to\\my\\file (Windows)

the error may be due to, the required xml files has not been loaded properly. Search for the file haarcascade_frontalface_default.xml by using the search engine of ur OS get the full path and put it as the argument to cv2.CascadeClassifier as string

Please do not copy paste the content of xml file, because once you paste it to notepad it will be saved a s text file. So directly download the file from the given source.

I ran into the same problem. but wrote the correct location.
face_cascade = cv2.CascadeClassifier('./model/haarcascade_frontalface_default.xml')
I figured out that i need to declare the full path to remove the error.
face_cascade = cv2.CascadeClassifier('C:/pythonScript/Facial-Emotion-Detection/model/haarcascade_frontalface_default.xml')

The error occurs due to missing of xml files or incorrect path of xml file.
Please try the following code,
import numpy as np
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,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()

I had the same problem with opencv-python and I used a virtual environment.
If it's your case, you should find the xml files at:
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml
Please be sure that you're using the absolute path. Otherwise, it won't work.

The main idea of the solution as above mentioned: find the right path of the .xml file and use it to access the file correctly.
In my case, I installed the opencv in anoconda env, first direct to path of Anoconda, then
find the path of .xml file by using:
$ find . -name 'haarcascade_eye.xml' (for example search the haarcascade_eye.xml file in current dir (.))
Then use the return path:
eye_cascade = cv2.CascadeClassifier(path + 'haarcascade_eye.xml')

I faced a similar issue. It seems correcting the path to XML makes this error to go away.

It seems to be file path issue. I changed code like this and it worked.
haar_face_filename = "D:\Sandbox\Github\Faces\haar_face.xml"
haar_cascade = cv.CascadeClassifier(haar_face_filename)

I had the same issue and was trying to use open cv in a springboot application where my xml files and images are in resources folder.
Trying to give path starting from src or a absolute path like C:\a\b.xml did not work.
Creating the file path dynamically with project root path worked.
String classifierPath = System.getProperty("user.dir") + "/src/main/resources/haarcascades/haarcascade_frontalface.xml";
// similarly for image paths

Path needs to start with /, eg. /file.xml.

Related

Python cannot find a directory

I wrote a code like this with jupyter notebook in a project;
import os
image_path = r'C:\Users\ays\Desktop\IR\01.jpg'
image_files = os.listdir(image_path)
img = cv2.imread(os.path.join(image_path,image_files))
cv2.imshow('image',img)
it gives an error like;
[WinError 3] The system cannot find the path specified: 'C:\Users\ays\Desktop\IR\01.jpg'
i was trying to print an image and
i had a directory problem
The argument to os.listdir() must be the directory, not the image file, so remove \01.jpg.
Then you'll need to loop over the result of os.listdir(), since it returns a list.
import os
image_path = r'C:\Users\ays\Desktop\IR'
image_files = os.listdir(image_path)
for file in image_files:
img = cv2.imread(os.path.join(image_path,file))
cv2.imshow('image',img)
Your image_path seems to be a file, not a directory. Drop the file name and you should be OK:
image_path = r'C:\Users\ays\Desktop\IR'

How to open a random image from specified folder/directory in Python OpenCV

I want my program to open a random image from the folder.
This works:
import cv2
import os
import random
capture = cv2.imread(".Images/IMG_3225.JPEG")
But when I want to do this random it doesn't work:
file = random.choice(os.listdir("./images/"))
capture = cv2.imread(file)
I'm getting the following error:
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
What am I doing wrong??
This happens because os.listdir returns the contents of a folder.
Having this folder structure:
images/
- a.png
- b.png
- c.png
This would be the expected result.
>>> os.listdir('images')
['a.png', 'b.png', 'c.png']
file actually contains the name of a file in images/, so cv2.imread does not find the file because it's looking for it in the wrong place.
You have to pass cv2.imread the path to the file:
IMAGE_FOLDER = './images'
filename = random.choice(os.listdir(IMAGE_FOLDER))
path = '%s/%s' % (IMAGE_FOLDER , filename)
capture = cv2.imread(path)
This is one of the small mistakes that we usually overlook while working on it. It is mainly because os.listdir returns the contents of a folder. When you are using os.listdir, it just returns file name. As a result it is running like capture = cv2.imread("file_name.png") whereas it should be capture = cv2.imread("path/file_name.png")
So when you are working, try to use the code snippet:
path = './images'
file = random.choice(os.listdir("./images/"))
capture = cv2.imread(os.path.join(path,file))
This will help you run the code.
Try this:
import os
import cv2
import random
dirs = []
for i in os.listdir("images"):
if i.endswith(".JPEG"):
dirs.append(os.path.join("images", i))
pic = random.choice(dirs)
pic_name = pic.split("\\")[-1]
pic = cv2.imread(pic)
cv2.imshow(pic_name, pic)
cv2.waitKey(0)

cv2.error: OpenCV(4.5.3) error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale' [duplicate]

I'm trying to learn cv2 in python 2.7, but when I run my code, in the specific part of it:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
it returns this:
File "face_detection.py", line 11, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/objdetect/src/cascadedetect.cpp:1595: error: (-215) !empty() in function detectMultiScale
I tried to search the answer here but the best i could find is that I must be loading the face_cascade the wrong way... Any help?
I had the same issue.
I didn't need to download anything else to solve this. CV2 had everything I needed.
Instead of trying to figure out where the .xml files are and hard coding the values, I used a property given by cv2.
From OP
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Becomes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML or file is missing or the path to it is incorrect or the create_capture path is incorrect.
The paths in the opencv sample look like this:
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')
I ran the same code. There are two things to note here.
1. Give the entire path of the .xml files.
2. Give a key press event instruction at the end.
Add this block of code at the end and run your file, worked for me:
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
For example, my code looked like
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)
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(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
My output looked like this:
You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML file is missing, you can get the file from the GitHub repository and place it in the same directory as your project. Link to the folder on GitHub is here. Just download the file named haarcascade_frontalface_default.xml.
Actually, the file exists on your system. Just go to the site-packages folder of your python installation folder and check the cv2/data folder for the file
Use the entire file path and use "\\" instead of "\" in the xml file path.
The file path should be as follows:
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
instead of:
cascade_fn = args.get('--cascade', "..\..\data\haarcascades\haarcascade_frontalface_alt.xml")
no need to change the code
download that .xml file , then put the path of that file
it will solve the error (100%)
If you are using Anaconda you should add the Anaconda path.
new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'
face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')
This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.
You can use the built-in pkg_resources module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2 module was loaded from:
import pkg_resources
haar_xml = pkg_resources.resource_filename(
'cv2', 'data/haarcascade_frontalface_default.xml')
For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'; yours is guaranteed to be different. Just let python’s pkg_resources library figure it out.
classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)
Success!
On OSX with a homebrew install the full path to the opencv folder should work:
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')
Take care of the version number in the path.
Probably the face_cascade is empty. You can check if the variable is empty or not by typing following command:
face_cascade.empty()
If it is empty you will get True and this means your file is not available in the path you mentioned.
Try to add complete path of xml file as follows:
r'D:\folder Name\haarcascade_frontalface_default.xml'
"\Anaconda3\Lib\site-packages\cv2\data\" I found the xml file in this path for Anaconda
You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example
This will not work
front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Use full path, now it will work fine
front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')
I found this in some other answer but eventually worked for me when I added the two answers.
import cv2
from matplotlib import pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
img = cv2.imread('image1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
You may find such kind of errors when you did not define the complete path of your XML file.
Try this one if you are using opencv3.1.0 in raspberrypi 3:
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
Your XML file was not found. Try using absolute paths like:
/path/to/my/file (Mac, Linux)
C:\\path\\to\\my\\file (Windows)
the error may be due to, the required xml files has not been loaded properly. Search for the file haarcascade_frontalface_default.xml by using the search engine of ur OS get the full path and put it as the argument to cv2.CascadeClassifier as string
Please do not copy paste the content of xml file, because once you paste it to notepad it will be saved a s text file. So directly download the file from the given source.
I ran into the same problem. but wrote the correct location.
face_cascade = cv2.CascadeClassifier('./model/haarcascade_frontalface_default.xml')
I figured out that i need to declare the full path to remove the error.
face_cascade = cv2.CascadeClassifier('C:/pythonScript/Facial-Emotion-Detection/model/haarcascade_frontalface_default.xml')
The error occurs due to missing of xml files or incorrect path of xml file.
Please try the following code,
import numpy as np
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,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()
I had the same problem with opencv-python and I used a virtual environment.
If it's your case, you should find the xml files at:
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml
Please be sure that you're using the absolute path. Otherwise, it won't work.
The main idea of the solution as above mentioned: find the right path of the .xml file and use it to access the file correctly.
In my case, I installed the opencv in anoconda env, first direct to path of Anoconda, then
find the path of .xml file by using:
$ find . -name 'haarcascade_eye.xml' (for example search the haarcascade_eye.xml file in current dir (.))
Then use the return path:
eye_cascade = cv2.CascadeClassifier(path + 'haarcascade_eye.xml')
I faced a similar issue. It seems correcting the path to XML makes this error to go away.
It seems to be file path issue. I changed code like this and it worked.
haar_face_filename = "D:\Sandbox\Github\Faces\haar_face.xml"
haar_cascade = cv.CascadeClassifier(haar_face_filename)
I had the same issue and was trying to use open cv in a springboot application where my xml files and images are in resources folder.
Trying to give path starting from src or a absolute path like C:\a\b.xml did not work.
Creating the file path dynamically with project root path worked.
String classifierPath = System.getProperty("user.dir") + "/src/main/resources/haarcascades/haarcascade_frontalface.xml";
// similarly for image paths
Path needs to start with /, eg. /file.xml.

How to move images to a different directory using Linux Ubuntu terminal

I am now trying to build a script that opens, rotates, resizes and saves several images contained in the images directory (running the pwd command gives the message /home/student-01-052f372bc989/images). The images contained in the images directory are of the format TIFF, have a resolution of 192x192 pixel and are rotated 90° anti-clockwise. The script must turn these images in the following formats:
.jpeg format
Image resolution 128x128 pixels
Should be straight
and save the modified images in the /opt/icons directory
Here is the code I currently have:
import os
from PIL import Image
Image_dir = '/home/student-01-052f372bc989/images'
imagedir = os.chdir(Image_dir)
new_dir = '/opt/icons'
for pic in os.listdir(os.getcwd()):
if pic.endswith(".tiff"):
img = Image.open(pic)
new_img = img.resize((128,128)).rotate(270)
newName = pic.replace(".tiff", ".jpeg")
newdir = os.chdir(new_dir)
new_img.save(newName, "JPEG")
imagedir = os.chdir(Image_dir)
The code has no issue when I run it, but when I run the ls /opt/icons command to check if the modified images were copied to the directory, the images are not yet there.
The script is currently located in the /home/student-01-052f372bc989/images directory.
Could someone please tell me what I did wrong?
So... with a bit of digging, i did manage to find an easier way to do the script
the code is as follows:
import os
from PIL import Image
old_path = os.path.expanduser('~') + '/images/'
new_path = '/opt/icons/'
for image in os.listdir(old_path):
if '.' not in image[0]:
img = Image.open(old_path + image)
img.rotate(-90).resize((128, 128)).convert("RGB").save(new_path + image.split('.')[0], 'jpeg')
img.close()

Opencv detectMultiScale error [duplicate]

I'm trying to learn cv2 in python 2.7, but when I run my code, in the specific part of it:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
it returns this:
File "face_detection.py", line 11, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/objdetect/src/cascadedetect.cpp:1595: error: (-215) !empty() in function detectMultiScale
I tried to search the answer here but the best i could find is that I must be loading the face_cascade the wrong way... Any help?
I had the same issue.
I didn't need to download anything else to solve this. CV2 had everything I needed.
Instead of trying to figure out where the .xml files are and hard coding the values, I used a property given by cv2.
From OP
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Becomes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML or file is missing or the path to it is incorrect or the create_capture path is incorrect.
The paths in the opencv sample look like this:
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')
I ran the same code. There are two things to note here.
1. Give the entire path of the .xml files.
2. Give a key press event instruction at the end.
Add this block of code at the end and run your file, worked for me:
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
For example, my code looked like
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)
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(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
My output looked like this:
You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML file is missing, you can get the file from the GitHub repository and place it in the same directory as your project. Link to the folder on GitHub is here. Just download the file named haarcascade_frontalface_default.xml.
Actually, the file exists on your system. Just go to the site-packages folder of your python installation folder and check the cv2/data folder for the file
Use the entire file path and use "\\" instead of "\" in the xml file path.
The file path should be as follows:
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
instead of:
cascade_fn = args.get('--cascade', "..\..\data\haarcascades\haarcascade_frontalface_alt.xml")
no need to change the code
download that .xml file , then put the path of that file
it will solve the error (100%)
If you are using Anaconda you should add the Anaconda path.
new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'
face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')
This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.
You can use the built-in pkg_resources module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2 module was loaded from:
import pkg_resources
haar_xml = pkg_resources.resource_filename(
'cv2', 'data/haarcascade_frontalface_default.xml')
For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'; yours is guaranteed to be different. Just let python’s pkg_resources library figure it out.
classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)
Success!
On OSX with a homebrew install the full path to the opencv folder should work:
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')
Take care of the version number in the path.
Probably the face_cascade is empty. You can check if the variable is empty or not by typing following command:
face_cascade.empty()
If it is empty you will get True and this means your file is not available in the path you mentioned.
Try to add complete path of xml file as follows:
r'D:\folder Name\haarcascade_frontalface_default.xml'
"\Anaconda3\Lib\site-packages\cv2\data\" I found the xml file in this path for Anaconda
You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example
This will not work
front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Use full path, now it will work fine
front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')
I found this in some other answer but eventually worked for me when I added the two answers.
import cv2
from matplotlib import pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
img = cv2.imread('image1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
You may find such kind of errors when you did not define the complete path of your XML file.
Try this one if you are using opencv3.1.0 in raspberrypi 3:
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
Your XML file was not found. Try using absolute paths like:
/path/to/my/file (Mac, Linux)
C:\\path\\to\\my\\file (Windows)
the error may be due to, the required xml files has not been loaded properly. Search for the file haarcascade_frontalface_default.xml by using the search engine of ur OS get the full path and put it as the argument to cv2.CascadeClassifier as string
Please do not copy paste the content of xml file, because once you paste it to notepad it will be saved a s text file. So directly download the file from the given source.
I ran into the same problem. but wrote the correct location.
face_cascade = cv2.CascadeClassifier('./model/haarcascade_frontalface_default.xml')
I figured out that i need to declare the full path to remove the error.
face_cascade = cv2.CascadeClassifier('C:/pythonScript/Facial-Emotion-Detection/model/haarcascade_frontalface_default.xml')
The error occurs due to missing of xml files or incorrect path of xml file.
Please try the following code,
import numpy as np
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,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()
I had the same problem with opencv-python and I used a virtual environment.
If it's your case, you should find the xml files at:
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml
Please be sure that you're using the absolute path. Otherwise, it won't work.
The main idea of the solution as above mentioned: find the right path of the .xml file and use it to access the file correctly.
In my case, I installed the opencv in anoconda env, first direct to path of Anoconda, then
find the path of .xml file by using:
$ find . -name 'haarcascade_eye.xml' (for example search the haarcascade_eye.xml file in current dir (.))
Then use the return path:
eye_cascade = cv2.CascadeClassifier(path + 'haarcascade_eye.xml')
I faced a similar issue. It seems correcting the path to XML makes this error to go away.
It seems to be file path issue. I changed code like this and it worked.
haar_face_filename = "D:\Sandbox\Github\Faces\haar_face.xml"
haar_cascade = cv.CascadeClassifier(haar_face_filename)
I had the same issue and was trying to use open cv in a springboot application where my xml files and images are in resources folder.
Trying to give path starting from src or a absolute path like C:\a\b.xml did not work.
Creating the file path dynamically with project root path worked.
String classifierPath = System.getProperty("user.dir") + "/src/main/resources/haarcascades/haarcascade_frontalface.xml";
// similarly for image paths
Path needs to start with /, eg. /file.xml.

Categories