如何在 python 中获取平面图的外部轮廓?

How to get the external contour of a floorplan in python?

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

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

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

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

代码片段可能如下所示:

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])