I am using the inbuilt cascade classifier for the face detection.
This is how the code is (OpenCV Python Tutorials):
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('ammma.jpg')
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)
cv2.waitKey(0)
cv2.destroyAllWindows()
But when I run the code I am getting the following error:
C:\Python27\python.exe C:/Users/DELL/Downloads/Amma/code/fd.py
OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp, line 1634
Traceback (most recent call last):
File "C:/Users/DELL/Downloads/Amma/code/fd.py", line 10, in
faces = face_cascade.detectMultiScale(img, 1.3, 5)
cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp:1634: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
Refer to this line of code, it failed on checking that cascade is non empty. Please check path to XML files with trained cascades. You may need to specify full path to XML's like this:
face_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_eye.xml')
Or just put this files to directory containig your script.
You do NOT need to download or copy the .xml files. According to the OpenCV-Python PyPi page, you can simply use the packaged path to the installed cascades - cv2.data.haarcascades:
import cv2
# Globals
FACE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
EYE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
SCALE_FACTOR = 1.3
BLUE_COLOR = (255, 0, 0)
MIN_NEIGHBORS = 5
# Then use it however you'd like
try:
faces = FACE_CLASSIFIER.detectMultiScale(gray, SCALE_FACTOR, MIN_NEIGHBORS)
for (x, y, w, h) in faces:
cv2.rectangle(self.roi_frame, (x, y), (x+w, y+h), BLUE_COLOR, HAAR_LINE_THICKNESS)
roi_gray = gray[y:y+h, x:x+w]
roi_color = self.roi_frame[y:y+h, x:x+w]
eyes = EYE_CLASSIFIER.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), GREEN_COLOR, HAAR_LINE_THICKNESS)
except Exception as e:
warnings.warn('{}.show_haar_features: got exception {}'.format(__name__, e))
I just happened to see this post when I faced a similar issue. I successfully resolved the error by executing the below 2 lines:
face_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_frontalface.xml')
eye_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_eye.xml')
Maybe, it will help others in resolving the same!
I faced the same problem. First you will have to give the correct path of the file to the system, which looks like this:
/home/xxxx/Desktop/Projects/haarcascade_eye.xml.
Next, you'll have to open the code on github and save the raw version of the code for it run.
It's advisable for both the files to be in the folder where you are storing your project file.
Happy coding
Well If you are getting this error then you need to download those 2 .xml files, because python can't find them on pc.
I had same problem, then I downloaded the .xml files and kept it in folder where my .py file is. and then I got the perfect output.
For downloading the files, search the file name and download it from sourceforge.
This post is old, but here is my answer nevertheless. Using absolute path did not work. Turns out that the XML file that I had downloaded (using curl) was corrupt. I had to manually copy and paste the contents from the github folder after which everything started working.
Zhanwen Chen's answer also works (which I believe is the right way to do it for in-built classifiers).
Maybe, you use virtualenv for python like me. You try this.
import os
base_directory = os.path.abspath(os.getcwd())
directory_cv2 = os.path.join(base_directory, "Lib", "site-packages", "cv2","data")
print("la carpeta es: {}".format(directory_cv2))
In newer versions of opencv haarcascades also gets installed you just need the file location of haarcascades, to get it you can use cv2.data.haarcascades just like shown below
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
https://github.com/udacity/P1_Facial_Keypoints/issues/13#issuecomment-385461579
After following the following comment. In you jupyter lab, open the kernel from the options where 'File', 'Edit', 'View', etc. Now choose, 'Change Kernel' and select 'Python [conda env:root]'.
Do this and you are done.
Related
I am trying to make a face detection python programme using opencv but when i run the following shell command I get the following error:
when i typed: python main2.py abba.png haarcascade_frontalface_default.xml
I am using opencv and I used the following documentationRealpython face Recognition:
(venv) C:\Users\User\PycharmProjects\main_1>python face_detect.py abba.png haarcascade_frontalface_default.xml
C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\User\PycharmProjects\main_1\face_detect.py': [Errno 2] No such file or directory
(venv) C:\Users\User\PycharmProjects\main_1>python main2.py abba.png haarcascade_frontalface_default.xml
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\main_1\main2.py", line 13, in <module>
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src
.empty() in function 'cv::cvtColor'
Here is the Code I used:
import sys
import cv2
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
This error indicates that the image file wasn't found correctly:
C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\User\PycharmProjects\main_1\face_detect.py': [Errno 2] No such file or directory
And thus it can't convert color using opencv of something (image) that's not a valid file.
File "C:\Users\User\PycharmProjects\main_1\main2.py", line 13, in <module>
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src
.empty() in function 'cv::cvtColor'
So, check if your folder contains the file you want to use, in your case: abba.png.
Use the command dir to list all the directories and files in a directory using windows cmd; ls is a unix command.
You can apply face detection within deepface. It wraps several face detectors. Here, mtcnn is the most robust but the slowest one. ssd is the fastest. The framework will download required dependencies in the background.
#!pip install deepface
from deepface import DeepFace
detectors = ['opencv', 'ssd', 'mtcnn', 'dlib']
img = DeepFace.detectFace("img.jpg", detector_backend = detectors[0])
I am using the inbuilt cascade classifier for the face detection.
This is how the code is (OpenCV Python Tutorials):
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('ammma.jpg')
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)
cv2.waitKey(0)
cv2.destroyAllWindows()
But when I run the code I am getting the following error:
C:\Python27\python.exe C:/Users/DELL/Downloads/Amma/code/fd.py
OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp, line 1634
Traceback (most recent call last):
File "C:/Users/DELL/Downloads/Amma/code/fd.py", line 10, in
faces = face_cascade.detectMultiScale(img, 1.3, 5)
cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp:1634: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
Refer to this line of code, it failed on checking that cascade is non empty. Please check path to XML files with trained cascades. You may need to specify full path to XML's like this:
face_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_eye.xml')
Or just put this files to directory containig your script.
You do NOT need to download or copy the .xml files. According to the OpenCV-Python PyPi page, you can simply use the packaged path to the installed cascades - cv2.data.haarcascades:
import cv2
# Globals
FACE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
EYE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
SCALE_FACTOR = 1.3
BLUE_COLOR = (255, 0, 0)
MIN_NEIGHBORS = 5
# Then use it however you'd like
try:
faces = FACE_CLASSIFIER.detectMultiScale(gray, SCALE_FACTOR, MIN_NEIGHBORS)
for (x, y, w, h) in faces:
cv2.rectangle(self.roi_frame, (x, y), (x+w, y+h), BLUE_COLOR, HAAR_LINE_THICKNESS)
roi_gray = gray[y:y+h, x:x+w]
roi_color = self.roi_frame[y:y+h, x:x+w]
eyes = EYE_CLASSIFIER.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), GREEN_COLOR, HAAR_LINE_THICKNESS)
except Exception as e:
warnings.warn('{}.show_haar_features: got exception {}'.format(__name__, e))
I just happened to see this post when I faced a similar issue. I successfully resolved the error by executing the below 2 lines:
face_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_frontalface.xml')
eye_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_eye.xml')
Maybe, it will help others in resolving the same!
I faced the same problem. First you will have to give the correct path of the file to the system, which looks like this:
/home/xxxx/Desktop/Projects/haarcascade_eye.xml.
Next, you'll have to open the code on github and save the raw version of the code for it run.
It's advisable for both the files to be in the folder where you are storing your project file.
Happy coding
Well If you are getting this error then you need to download those 2 .xml files, because python can't find them on pc.
I had same problem, then I downloaded the .xml files and kept it in folder where my .py file is. and then I got the perfect output.
For downloading the files, search the file name and download it from sourceforge.
This post is old, but here is my answer nevertheless. Using absolute path did not work. Turns out that the XML file that I had downloaded (using curl) was corrupt. I had to manually copy and paste the contents from the github folder after which everything started working.
Zhanwen Chen's answer also works (which I believe is the right way to do it for in-built classifiers).
Maybe, you use virtualenv for python like me. You try this.
import os
base_directory = os.path.abspath(os.getcwd())
directory_cv2 = os.path.join(base_directory, "Lib", "site-packages", "cv2","data")
print("la carpeta es: {}".format(directory_cv2))
In newer versions of opencv haarcascades also gets installed you just need the file location of haarcascades, to get it you can use cv2.data.haarcascades just like shown below
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
https://github.com/udacity/P1_Facial_Keypoints/issues/13#issuecomment-385461579
After following the following comment. In you jupyter lab, open the kernel from the options where 'File', 'Edit', 'View', etc. Now choose, 'Change Kernel' and select 'Python [conda env:root]'.
Do this and you are done.
I am trying to resolve captcha for the following image
!https://ibb.co/35X723J
I have tried using tessaract
data = br.open(captchaurl).read()
b = bytearray(data)
save = open(filename, 'wb')
save.write(data)
save.close()
ctext= pytesseract.image_to_string(Image.open(filename))
Here is a workaround. You need to clear a bit the image but you wont get a perfect result. Try the following:
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
import cv2
file = 'sample.jpg'
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, None, fx=10, fy=10, interpolation=cv2.INTER_LINEAR)
img = cv2.medianBlur(img, 9)
th, img = cv2.threshold(img, 185, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("sample2.jpg", img)
file = 'sample2.jpg'
text = pytesseract.image_to_string(file)
print(''.join(x for x in text if x.isdigit()))
Option 1:
I think using Pytesseract should solve the issue. I tried out your code and it gave me the following result when i gave in the exact cropped captcha image as input into pytesseract:
Input Image:
Output:
print(ctext)
'436359 oS'
I suggest you don't give the full page url as input into pytesseract. Instead give the exact image url as "https://i.ibb.co/RGn9fF5/Jpeg-Image-CS2.jpg" which will take in only the image.
And regarding the extra 'oS' characters in the output, you can do a string manipulation to chop off the characters other than numbers in the output.
re.sub("[^0-9]", "", ctext)
Option 2:
You can also use google's OCR to accomplish this which gives you the exact result without errors. Though I have shown you the web interface of it, google has nice python libraries through which you can accomplish this using python itself. Looks like this:
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.
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()
cv2.destroyAllWindows()
This is the code
sys.argv[1] is the first CLI parameter and if you don't provide any CLI parameter, len(sys.argv)=1 so you can only access sys.argv[0] which is the script name.
What you need to do is provide a CLI parameter which is for cascPath.
The Cascade is a xml file contains OpenCV data to detect objects which might comes with the tutorial you read / the code snippet you downloaded.
You code snippet looks identical to the code written by Shantnu Tiwari. See the webpage https://realpython.com/face-detection-in-python-using-a-webcam/. Here he analyzes the code and has a video clip showing the face-detection-code in action.
Goto Shantus's GitHub site https://github.com/shantnu/Webcam-Face-Detect to download the python-code and the file "haarcascade_frontalface_default.xml". This xml-file contains all information that the haarcascade algorithmn in OpenCV needs. Run:
python webcam.py haarcascade_frontalface_default.xml
You'll find more xml files for various detections (eyes, full body, ...) on the OpenCV GitHub site:
https://github.com/opencv/opencv/tree/master/data/haarcascades
Had that same error. Reasons for the error have been explained here already. You just need to provide the path to the "haarcascade_frontalface_default.xml" file you downloaded. That is, instead of
cascPath = sys.argv[1], use:
cascPath = haarcascade_frontalface_default.xml, if your python and xml files are in the same directory.
Otherwise, you can compile your code on the python shell thus; python webcam.py haarcascade_frontalface_default.xml.
I have no problem getting the opencv face detection using haar feature based cascades working on saved images:
from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('pic.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
but I can't figure out how to open a url image and pass it into face_cascade. I've been playing around with cStringIO, but I don't know what to do with it...
import cv2.cv as cv
import urllib, cStringIO
img = 'http://scontent-b.cdninstagram.com/hphotos-prn/t51.2885-15/10424498_582114441904402_1105042543_n.png'
file = cStringIO.StringIO(urllib.urlopen(img).read())
source = Image.open(file).convert("RGB")
bitmap = cv.CreateImageHeader(source.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring())
cv.CvtColor(bitmap, bitmap, cv.CV_RGB2BGR)
is it possible to work with a numpy array instead?
source2 = Image.open(file)
imarr=numpy.array(source2,dtype=numpy.uint8)
I'm a beginner, so I apologize for the poor explanation.
thanks a lot in advance!!
In your first example you are using OpenCV2.imread to read your image in the second you are presumably using PIL.Image then trying to convert.
Why not simply save the file to a temp directory and then use OpenCV2.imread again?
Or in another way you can use VideoCapture() class to open url image.
See the C++ code below,
VideoCapture cap;
if(!cap.open("http://docs.opencv.org/trunk/_downloads/opencv-logo.png")){
cout<<"Cannot open image"<<endl;
return -1;
}
Mat src;
cap>>src;
imshow("src",src);
waitKey();