FindContours操作后只提取一个轮廓



我目前正在使用FindContours和DrawContours函数来分割图像。

我只提取外部轮廓,并且只想保存包含给定点的轮廓。我使用h_next通过cv_seq结构移动,并使用PointPolygonTest测试是否包含该点

我实际上可以找到我感兴趣的轮廓,但我的问题是提取它。

下面是python代码:
def contour_from_point(contours, point, in_img):
"""
Extract the contour from a sequence of contours which contains the point.
For this to work in the eagle road case, the sequence has to be performed using the 
FindContours function with CV_RETR_EXTERNAL
"""
if contours:
    # We got at least one contour. Search for the one which contains point
    contour = contours # first contour of the list
    distance = cv.PointPolygonTest(contour, point, 0)
    while distance < 0: # 0 means on eadge of contour
        contour = contour.h_next()       
        if contour: # avoid end of contours
            distance = cv.PointPolygonTest(contour, point, 0)
        else : 
            contour = None
else:# 
    contour = None  
return contour

最后,我得到了轮廓。但这个结构仍然包含所有尚未测试的轮廓。我怎样才能只保留输出序列的第一个轮廓?

提前感谢!

最后有一种方法可以只得到一个轮廓。只需使用另一个需要cvseq输入的函数,例如ConvexHull。输出将只是序列的第一个轮廓。

最新更新