如何在OpenCV python中忽略内部黑色轮廓? [英] How to ignore inner black contours in OpenCV python?

查看:70
本文介绍了如何在OpenCV python中忽略内部黑色轮廓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上图中,我仅需要以下轮廓:8、7、0、2、4.

In the above image, I only need the following contours: 8, 7, 0, 2, 4.

其中每个其他轮廓为黑色的空盒子.有没有一种方法可以使用cv2.RETR_TREE自动提取此类轮廓?

Every other contour black empty boxes inside them. Is there a way to automatically extract only such contours using cv2.RETR_TREE?

cv2.RETR_EXTERNAL将忽略我实际需要的2和4

cv2.RETR_EXTERNAL will ignore 2 and 4 which I actually need

       >>heirarchy

       >>array([[[ 7, -1,  1, -1],

        [-1, -1,  2,  0],

        [-1, -1,  3,  1],

        [-1, -1,  4,  2],

        [-1, -1,  5,  3],

        [ 6, -1, -1,  4],

        [-1,  5, -1,  4],

        [ 8,  0, -1, -1],

        [-1,  7, -1, -1]]])

如何从上述层次结构中仅提取外部轮廓,而不排除2和4并忽略1、3、5、6,因为这四个轮廓内部仅包含空白区域?

How can I extract from the above heirarchy only the external contours but not exlcuding 2 and 4 and ignoring 1, 3, 5, 6 since those four contours contain just empty regions inside?

推荐答案

如果您可以自由使用cv2.RETR_TREE以外的任何其他方法,则可以使用cv2.RETR_CCOMP将轮廓仅分为两个层次,即外部和内部.您只能选择其父索引(索引3的值)为-1的轮廓."-1"表示轮廓没有任何父级.您只会得到以下轮廓:8、7、0、2、4.

If you are free to use any other method than cv2.RETR_TREE , then you can use cv2.RETR_CCOMP which divides contours in only two level hierarchy i.e outer and inner. You can only pick those contours whose parent index (value at index 3) is -1. '-1' denotes that the contours do not have any parent. You will only get the following contours: 8, 7, 0, 2, 4.

参考文献: https://docs.opencv.org/3.4/d9/d8b/tutorial_py_contours_hierarchy.html

这篇关于如何在OpenCV python中忽略内部黑色轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆