Contouring a binary mask with OpenCV / Python

折月煮酒 提交于 2019-12-05 21:44:17

Until OpenCV 3.1 findContours has this wierd behaviour on borders, also stated in the documentation:

Source image is modified by this function. Also, the function does not take into account 1-pixel border of the image (it's filled with 0's and used for neighbor analysis in the algorithm), therefore the contours touching the image border will be clipped.

This has been corrected in OpenCV 3.2, which also doesn't modify the source image:

Since opencv 3.2 source image is not modified by this function.


As a workaround for previous releases, you can use copyMakeBorder to create a black (0) border of 1 pixel, and use findContours with an offset of (-1,-1):

border = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0 )
_, contours, hierarchy = cv2.findContours(border, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(-1, -1))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!