error: (-215:Assertion failed) !empty() in function CV2 Error - python

I am making a program in python that just draws a rectangle around a car. I am currently stuck on getting the coordinates of the car, here is the code:
#################################################
import cv2
#################################################
car_data = cv2.CascadeClassifier(cv2.data.haarcascades + "cars.xml")
img = cv2.imread("car_front.jpeg")
#################################################
img_but_bnw = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
car_coordinates = car_data.detectMultiScale(img_but_bnw)
print(car_coordinates)
#################################################
cv2.imshow("Detect Everything", img_but_bnw)
cv2.waitKey()
print("Code Completed")
#################################################
I am running in on an error with the function "cv2.detectMultiScale".
error:
File "e:\Python2\Body_Detection.py", line 11, in <module>
car_coordinates = car_data.detectMultiScale(img_but_bnw)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
I have tried googling, it says to use cv2.CascadeClassifier(cv2.data.haarcascades + "cars.xml") instead of cv2.CascadeClassifier("cars.xml"). It didn't work :(, Any help would be appreciated.

The file cars.xml is not part of the opencv library although you may find tutorials in the internet that use this filename. The folder addressed by cv2.data.haarcascades includes xml examples for things like eye and face detection (current content see https://github.com/opencv/opencv/tree/master/data).
You can search for an existing cars.xml example by other authors and copy it to your project folder. Then just use "cars.xml" without cv2.data.haarcascades.
E.g. I found this project Vehicle Detection with Haar Cascades that includes a file cars.xml working fine with your code above.

Related

Python opencv error (-215:Assertion failed) 0 <= scaleIdx && scaleIdx < (int)scaleData->size() in CascadeClassifier.detectMultiScale

I'm using the CascadeClassifier of the opencv-python package to perform face detection with the haarcascade_frontalface_default.xml with this code:
self.face_cascade = cv2.CascadeClassifier(haar_cascade_path)
...
gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(gray_frame, 1.3, 5)
It's working fine for most of the frames, but sometimes I'm getting this exception:
cv2.error: OpenCV(4.6.0) d:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\cascadedetect.hpp:46: error: (-215:Assertion failed) 0 <= scaleIdx && scaleIdx < (int)scaleData->size() in function 'cv::FeatureEvaluator::getScaleData'
The error occurs during the detectMultiScale call. I already checked the gray_frame and it looks good (shape is 1366x1060 and it's not none or something like that). Do you have any idea on how the fix this?
I actually managed to solve this issue. What caused this error to happen was, that I'm preprocessing the dataset multithreaded and I only used a single instance for multiple workers concurrently. It seems like the CascadeClassifier (or at least the detect method) isn't thread-safe and feeding images with a different size concurrently caused the problem. Creating one instance for each thread/worker solved the issue.

Python: cv2 can't open USB camera. "error: (-215:Assertion failed)"

I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting:
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor
So I've tried using various index (from -1 to 5) in this line of code:
cap = cv2.VideoCapture(0)
But nothing changed, I've also tried to use:
cd /dev
ls video
But this is the error I'm getting:
ls: cannot access 'video': No such file or directory
Is there a way to fix this problem?
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
Before this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address if there is any. Best:)

Error: Bad argument (Layer "crop" already was registered)

The Problem
I have a problem when I am trying to automate a CNN Canny Edge detection pipeline, where many files are given as input and each is run through the Canny Edge detection CNN algorithm.
Here is the code that runs the algorithm on each given image (tiffs are in a folder, each should be processed using the CNN Canny algorithm):
files = get_files(TIF_DIR)
for f in files:
get_edges(f, OUT_DIR)
The code successfully processes one image, but subsequent attempts to process other images produces the error:
OpenCV: terminate handler is called! The last OpenCV error is:
OpenCV(4.0.1) Error: Bad argument (Layer "crop" already was registered) in cv::dnn::dnn4_v20181221::LayerFactory::registerLayer, file C:\ci\opencv-suite_1573470242804\work\modules\dnn\src\dnn.cpp, line 3629
This is the function that I believe the error comes from. I have tried:
making the three lines under 'setting up the layer' only run the first time the function is called, but the error persists.
Using cv.dnn_unregisterLayer('Crop'), but the problem persists with the same error
Renaming the Layer that I'm adding from 'Crop' to 'test', but the error stays the same. This leads me to think that it may not be the layer that I am manually adding that is the problem.
def get_edges(infile, outfolder):
head_tail = os.path.split(infile)
outpath = os.path.join(OUT_DIR, head_tail[1][:-3] + "_edge.png")
if os.path.isfile(outpath):
return 0
cap = cv.VideoCapture(infile)
hasFrame, frame = cap.read()
# Setting up layer
cv.dnn_registerLayer('Crop', CropLayer)
net = cv.dnn.readNet(os.path.abspath('deploy.prototxt'), os.path.abspath('hed_pretrained_bsds.caffemodel'))
inp = cv.dnn.blobFromImage(frame, scalefactor = 1.0, crop = False)
# Outputting from net...
net.setInput(inp)
out = net.forward()
out = out[0, 0]
out = 255 * out
out = out.astype(np.uint8)
cv.imwrite(outpath, out)
Thanks for your help!
Specifications:
Python version 3.8.5
OpenCV version 4.0.1
Windows 10.0.19042

Error while trying to access phone camera with opencv python

I expected to receive a video feed in my laptop from my phone. In my opinion, the code is correct. The same code is running on other devices. But when I tried doing the same in my laptop, it displayed the following error:
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap.cpp (142) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): http://192.168.1.3:8080/video in function 'cv::icvExtractPattern'
Since I am a newbie to the world of opencv, I could'nt understand what caused the error. Hence, I did'nt try anything worthwhile other than changing a few lines of code.
My code is:
import cv2
url= 'http://192.168.1.3:8080/video'
cap=cv2.VideoCapture(url)
cap.set(3,240)
cap.set(4,240)
while(True):
ret,frame=cap.read()
if frame is not None:
cv2.imshow('frame',frame)
q=cv2.waitKey(1)
if q==ord("q"):
break
cv2.destroyAllWindows()
cap.release()
I had encountered the same issue but with a a saved video file as the input.
The file path I had entered did no exist and I got the same error.
I would suggest to check if your have given the right permissions to for accessing your phone's camera and if the feed is live and is returning images in the correct format.

OpenCV (-215:Assertion failed) !_src.empty()

I am trying to do a basic emotion recognition with fisherface in python however I can't seem to get past the below error. It is trying to read .jpg files in folders. I have re-installed python and OpenCV(4.1.0) but still same error.
Here is the code that fails:
emotions = ["anger", "neutral", "contempt", "disgust", "happy", "happy", "sadness", "surprise"] #Emotion list
fishface = cv2.face.FisherFaceRecognizer_create() #Initialize fisher face classifier
def get_files(emotion):
files = glob.glob("C:\\Users\\Noel\\Documents\\Project AI\\Phyton\\dataset\\%s\\*" %emotion)
random.shuffle(files)
This is the error message:
error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
I tried arranging the path and also tried to move the folder to a new location.

Categories

Resources