0
votes
import numpy as np
import cv2

img = cv2.imread("/home/user/Pictures/shapes_and_colors.png")
_,threshold = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),60,255,cv2.THRESH_BINARY)
_,contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    [x,y,w,h] = cv2.boundingRect(contour)

enter image description here

I got this error

error: OpenCV(4.2.0) /io/opencv/modules/imgproc/src/shapedescr.cpp:784: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'pointSetBoundingRect'

How to remove this error.

1
Stack trace pleaseMad Physicist

1 Answers

0
votes

You mixed the order of cv2.findContours output arguments.

Use:

contours, _ = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

Instead of:

_, contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

In OpenCV 4, the first output argument is contours and second is hierarchy.
For backward compatibility with OpenCV 3, you may also use:

contours = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]