OpenCV中删除轮廓内的轮廓

OpenCV中删除轮廓内的轮廓

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

问题描述

Python中的OpenCV提供以下代码:

OpenCV in Python provides the following code:

regions, hierarchy = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)


for region in regions:
    x, y, w, h = cv2.boundingRect(region)

    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 1)

这会在轮廓内给出一些轮廓.如何在Python中删除它们?

This gives some contours within contour. How to remove them in Python?

推荐答案

为此,您应该看看本教程关于如何使用方法 findContours 返回的层次结构对象.

For that, you should take a look at this tutorial on how to use the hierarchy object returned by the method findContours .

要点是,您应该使用 cv2.RETR_TREE 而不是 cv2.RETR_LIST 来获取群集之间的父/子关系:

The main point is that you should use cv2.RETR_TREE instead of cv2.RETR_LIST to get parent/child relationships between your clusters:

regions, hierarchy = cv2.findContours(binary_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

然后,您可以通过检查 hierarchy [0,i,3] 是否等于-1来检查索引为 i 的轮廓是否在另一个轮廓内.如果它不同于-1,则说明您的轮廓位于另一个轮廓内.

Then you can check whether a contour with index i is inside another by checking if hierarchy[0,i,3] equals -1 or not. If it is different from -1, then your contour is inside another.

这篇关于如何在Python OpenCV中删除轮廓内的轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:08