Issue with precision of cv2.findContours

I have an issue of precision with findcontour that I have documented here : python - Issue with precision of cv2.findContours - Stack Overflow

Any chance someone knows why this happens and how to solve the problem ?

that involves matplotlib. what you see might be an issue of how matplotlib maps images to its coordinate system.

you can also see that matlab is inconsistent in its contour extraction. the outer one can do diagonal moves, the inner one never does that. both have diagonal pixel edges to traverse.

the behavior of OpenCV is to step on the centers of the white pixels of a blob. that’s done so the result is integer. I don’t like it either. I’d rather have something that gives me a polygon running along pixels’ edges.

>>> im = np.zeros((10,10), 'u1'); im[3:6,5] = 99
>>> im
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0, 99,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0, 99,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0, 99,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0]], dtype=uint8)

>>> (cnts, *_) = cv.findContours(im, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)

>>> cnts[0]
array([[[5, 3]],
       [[5, 4]],
       [[5, 5]],
       [[5, 4]]], dtype=int32)

>>> cv.contourArea(cnts[0])
0

so you see, for a 1-pixel wide line, you get a flat contour of no area.

if anyone cares to create an issue about this, suggesting a new retrieval mode or flag, or even work on a pull request, I’d be thrilled.

thank you for your reply. I will open an issue then. Because it creates problems with regionprops of skimage. When I generate the corresponding label array (following the solution you gave me here python - label associated to findcontour with opencv - Stack Overflow ) to be then used in regionprops, it won’t generate properly the hollow ellipse since it uses findcontours and hence regionprops won’t consider a closed object since the two contours collapse on the sides.

1 Like

For anyone who has a solution, the issue on github is referenced here : Propose a new retrieval mode · Issue #21720 · opencv/opencv · GitHub