gpt4 book ai didi

python - 使用 Python 从 map 图像中提取建筑物边缘

转载 作者:行者123 更新时间:2023-12-01 00:48:45 26 4
gpt4 key购买 nike

我在这里得到了一张 map 图像。我需要提取建筑物的边缘进行进一步处理,结果就像帖子here的步骤2一样.

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

map image

最佳答案

似乎你想选择单独的建筑物,所以我使用了分色。墙壁较暗,这使得 HSV colorspace 中的分隔效果很好。 。请注意,可以通过放大更多和​​/或使用压缩率较低的图像类型(例如 PNG)来改善最终结果。

选择墙壁
首先,我确定了良好的分离值。为此,我使用了 this script 。我发现最好的结果是将黄色和灰色分开,然后组合所得的蒙版。并非所有墙壁都完美关闭,因此我将结果改进为 closing面具一点。结果是一个显示所有墙壁的 mask :

enter image description here从左到右:黄色蒙版、灰色蒙版、组合固化蒙版

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

enter image description herefindContours的结果:所有等高线的轮廓为绿色,个别建筑物的轮廓为红色

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

代码:

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

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

enter image description here

关于python - 使用 Python 从 map 图像中提取建筑物边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com