使用 Python 从地图图像中提取建筑物边缘

Pet*_*ete 2 python opencv image-processing edge-detection

我这里有一张地图图像。我需要提取建筑物的边缘以进行进一步处理,结果将类似于此处帖子的步骤 2 。

由于我对这个领域不熟悉,可以通过OpenCV等库来完成吗?

地图图像

J.D*_*.D. 5

看来你想选择个别建筑物,所以我使用了分色。墙壁较暗,这有助于在HSV 色彩空间中实现良好的分离。请注意,可以通过放大更多和​​/或使用压缩率较低的图像类型(例如 PNG)来改善最终结果。

选择墙壁
首先,我确定了良好的分隔值。为此我使用了这个脚本。我发现最好的结果是将黄色和灰色分开,然后组合所得的蒙版。并非所有墙壁都完美关闭,因此我通过稍微关闭遮罩来改善结果。结果是一个显示所有墙壁的遮罩:

在此输入图像描述 从左到右:黄色蒙版、灰色蒙版、组合固化蒙版

查找建筑物
接下来我使用findCountours来分离出建筑物。由于墙壁轮廓可能不是很有用(因为墙壁是互连的),因此我使用层次结构来查找“最低”轮廓(内部没有其他轮廓)。这些是建筑物。

在此输入图像描述 findContours的结果:所有等高线的轮廓为绿色,个别建筑物的轮廓为红色

请注意,不会检测到边缘的建筑物。这是因为使用这种技术它们不是单独的轮廓,而是图像外部的一部分。这可以通过在图像边框上绘制一个灰色矩形来解决。您可能不希望在最终申请中包含此内容,但我将其包含在您的最终申请中。

代码:

    import cv2
    import numpy as np  

    #load image and convert to hsv
    img = cv2.imread("fLzI9.jpg")

    # draw gray box around image to detect edge buildings
    h,w = img.shape[:2]
    cv2.rectangle(img,(0,0),(w-1,h-1), (50,50,50),1)

    # convert image to HSV
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # define color ranges
    low_yellow = (0,28,0)
    high_yellow = (27,255,255)

    low_gray = (0,0,0)
    high_gray = (179,255,233)

    # create masks
    yellow_mask = cv2.inRange(hsv, low_yellow, high_yellow )
    gray_mask = cv2.inRange(hsv, low_gray, high_gray)

    # combine masks
    combined_mask = cv2.bitwise_or(yellow_mask, gray_mask)
    kernel = np.ones((3,3), dtype=np.uint8)
    combined_mask = cv2.morphologyEx(combined_mask, cv2.MORPH_DILATE,kernel)

    # findcontours
    contours, hier = cv2.findContours(combined_mask,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # find and draw buildings
    for x in range(len(contours)):
            # if a contour has not contours inside of it, draw the shape filled
            c = hier[0][x][2]
            if c == -1:
                    cv2.drawContours(img,[contours[x]],0,(0,0,255),-1)

    # draw the outline of all contours
    for cnt in contours:
            cv2.drawContours(img,[cnt],0,(0,255,0),2)

    # display result
    cv2.imshow("Result", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows() 
Run Code Online (Sandbox Code Playgroud)

结果:
建筑物绘制为纯红色,所有轮廓绘制为绿色覆盖

在此输入图像描述