cv2.error (-215:Assertion failed) reader.ptr != NULL in function cvDrawContours

Viewed 2968

So I'm trying to create a license plate detection program and I have been following a guide for that, (https://github.com/nicknochnack/ANPRwithPython/blob/main/ANPR%20-%20Tutorial.ipynb) however I am currently running into a problem.

img = cv2.imread('image4.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

bfilter = cv2.bilateralFilter(gray, 11, 17, 17) #Noise reduction
edged = cv2.Canny(bfilter, 30, 200) #Edge detection

keypoints = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(keypoints)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]

location = None
for contour in contours:
    approx = cv2.approxPolyDP(contour, 10, True)
    if len(approx) == 4:
        location = approx
        break

mask = np.zeros(gray.shape, np.uint8)
new_image = cv2.drawContours(mask, [location], 0,255, -1)
new_image = cv2.bitwise_and(img, img, mask=mask)

I have also tried to change "location" to 0 or [0] but to no success.

2 Answers

Found the "solution" to this, although it's not much an Solution. The reason this kept happening is because the images I have been testing with, didn't have any recognizable shapes in it, so since it was not able to set "location", it also wasn't able to call the function properly. Hopefully someone who runs into this issue sees this and checks their data.

I 've just run into the same issue, and indeed it seems due to the fact that there are no contours/shapes to recognize.

In my case, i'm extracting each page of a pdf (a text pdf) as an image. This error comes because the output images are 1x1 white pixel images, so indeed there are no contours/shapes on these "images". If you run into the same issue as me, here is the link that helped me fix this: https://github.com/Belval/pdf2image/issues/34

I just have to had the parameter size= to get rid of the issue, as shown here:

from pdf2image import convert_from_path
convert_from_path("test.pdf", size=(3000,))[0].save("out.png")
Related