Error: (-215:Assertion failed) npoints > 0 while working with contours using OpenCV

Issue

When I run this code:

import cv2

image = cv2.imread('screenshoot10.jpg')
cv2.imshow('input image', image)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

edged = cv2.Canny(gray, 30, 200)
cv2.imshow('canny edges', edged)

_, contours = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('canny edges after contouring', edged)

print(contours)
print('Numbers of contours found=', len(contours))

cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
cv2.imshow('contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

I am getting this error:

OpenCV(4.1.1)
C:\projects\opencv-python\opencv\modules\imgproc\src\drawing.cpp:2509:
error: (-215:Assertion failed) npoints > 0 in function
‘cv::drawContours’

What am I doing wrong?

Solution

According to the documentation for findContours, the method returns (contours, hierarchy), so I think the code should be:

contours, _ = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

instead of

_, contours = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

Answered By – Ricardo Abe

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.