There are a bunch of questions about this function throwing errors, such as here and here but I think mine has a unique twist. What I'm trying to do is go through all the images in a folder and detect any faces.
import cv2
import sys
import os
#Get the folder to be searched and the location of the cascade file from arguments
imageDirectory = sys.argv[1]
cascadePath = sys.argv[2]
faceCascade = cv2.CascadeClassifier(cascadePath)
#Iterate over the png files in the directory
for imagePath in os.listdir(imageDirectory):
if imagePath.endswith(".png"):
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
#flags = cv2.CV_HAAR_SCALE_IMAGE
)
The first image will be processed correctly, but then the second will throw an error:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /tmp/opencv3-20170202-24427-1s95vpr/modules/imgproc/src/color.cpp, line 9748
Traceback (most recent call last):
File "face_detect_flip.py", line 22, in
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: /tmp/opencv3-20170202-24427-1s95vpr/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor
The files are all color .pngs so I can't tell why the script will work on some of them but not others. Sometimes changing the order or the filename (but not the extension) will change whether the script runs or not, but not in any pattern that I can discern.
Looks like the image that causes this error does not have 3 (rgb image) or 4 (rgba image) channels. The cvtColor function needs the the image to have at least 3 channels to convert it.
One possible reason could be that the file isn't being read correctly. This would cause the variable image to be None and hence it wont have the correct number of channels.
Another reason could be if the image has fewer channels. Maybe it's a grayscale image to begin with and thus has only one channel.
You can use print(image.shape) to check the number of channels. If the value is None then the file wasn't read correctly.
Related
When I load a set of image files into a list and try to display one, it always renders as a gray box.The images are not gray boxes. The size of the image window displayed by openCV varies with the size of the actual image on file.
import cv2
import glob
import random
def loadImages(path):
imdir = path
ext = ['png', 'jpg', 'gif'] # Add image formats here
files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
#print("files", files)
images = [cv2.imread(file) for file in files]
return images
images = loadImages("classPhotos/")
print(str(len(images)), "images loaded")
#print(images)
cv2.imshow("image", random.choice(images))
tmp = input()
Add this 2 lines after cv2.imshow("image", random.choice(images)) to make it work properly.
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow shows the image instantly and then doesn't show it.
cv2.waitKey waits for a specific time/ keeps showing the image.
putting 0 as an argument makes it wait infinitely unless a key is pressed.
cv2.destroyAllWindows() helps close the window otherwise it gets stuck.
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 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 want to convert a jpg file to png, but when I run this code :
from opencv import _cv
from opencv.highgui import cvSaveImage, cvLoadImage
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
if __name__ == '__main__':
pass
It gives this error which I don't understand :
Traceback (most recent call last):
File "convert.py", line 6, in <module>
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
File "/usr/lib/pymodules/python2.6/opencv/highgui.py", line 183, in cvSaveImage
return _highgui.cvSaveImage(*args)
RuntimeError: openCV Error:
Status=Null pointer
function name=cvGetMat
error message=NULL array pointer is passed
file_name=cxarray.cpp
line=2780
I have my picture with the same folder of source code and the name of the image is bet.jpg
Any idea ??
The best choice is pyopencv:
import pyopencv as cv
img = cv.imread('01.png')
cv.imshow('img-windows',img)
cv.waitKey(0)
cv.imwrite('01.png',img)
From Python CV documentation, the CV2 method for converting a jpeg to png is:
Python: cv2.imwrite(filename, img[, params]) → retval
For my example:
import cv2
filename = 'pic.jpeg'
cam = cv2.VideoCapture(filename)
s, img = cam.read()
picName = 'pic.png'
cv2.imwrite(picName, img)
VideoCapture is nice and general, and works with videos, webcams and image files.
I solved the problem, the image I took randomly from the Google Images doesn't load. Maybe it's encrypted or something I don't know. I tried it with other images, and worked very well. So watch out while copying images : )