【问题标题】:How to get the external contour of a floorplan in python?如何在python中获得平面图的外部轮廓?
【发布时间】:2016-07-14 05:53:40
【问题描述】:

获得平面图外部轮廓的最佳方法是什么?

Snakes 算法效果不佳,因为某些平面图过于凸。

【问题讨论】:

    标签: opencv image-processing scikit-image


    【解决方案1】:

    你只需要在寻找轮廓时调整灰度图像的阈值以包含灰色虚线路径,由于输入图像的主要部分是白色的,所以我们可以选择接近 255 的阈值,比如 230。然后找到轮廓阈值。

    您可以使用cv2.approxPolyDP 来计算近似多项式形状,但这并没有太大帮助,因此该步骤是可选的。

    代码 sn-p 可能如下所示:

    import cv2
    
    img = cv2.imread("/Users/anmoluppal/Downloads/1tl6D.jpg")
    
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    ret, thresh = cv2.threshold(img_gray, 230, 255, cv2.THRESH_BINARY_INV)
    
    img_, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    largest_contour_area = 0
    for cnt in contours:
        if (cv2.contourArea(cnt) > largest_contour_area):
            largest_contour_area = cv2.contourArea(cnt)
            largest_contour = cnt
    
    epsilon = 0.001*cv2.arcLength(largest_contour,True)
    approx = cv2.approxPolyDP(largest_contour,epsilon,True)
    
    final = cv2.drawContours(img, [approx], 0, [0, 255, 0])
    

    【讨论】:

    • 太棒了。只需更改第 5 行,以便:contours、hierarchy = cv2.findContours(...) 并且如果 contours 为空,则不会分配最大轮廓。
    • cv2.findContours 在 Opencv 3.1 中返回 3 个值,但在 Opencv2.7 中仅返回 2 个值。所以那个东西是版本相关的,你需要计算最大的轮廓,因为图像中可能会形成一些需要忽略的小轮廓。
    • 好的。关于最大的轮廓,我的意思是在“轮廓”为空的情况下......
    猜你喜欢
    • 2012-11-15
    • 2013-12-22
    • 2020-03-14
    • 2019-03-23
    • 2019-01-25
    • 2022-01-10
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多