python - 如何识别平面图的形状?
问题描述
我正在尝试使用平面图来区分两种不同风格的房屋。我很新cv2
,所以我在这里有点挣扎。我可以使用下面的代码使用轮廓识别房屋的外部,即来自另一个 Stack Overflow 响应。
import cv2
import numpy as np
def find_rooms(img, noise_removal_threshold=25, corners_threshold=0.1,
room_closing_max_length=100, gap_in_wall_threshold=500):
assert 0 <= corners_threshold <= 1
# Remove noise left from door removal
img[img < 128] = 0
img[img > 128] = 255
contours, _ = cv2.findContours(~img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros_like(img)
for contour in contours:
area = cv2.contourArea(contour)
if area > noise_removal_threshold:
cv2.fillPoly(mask, [contour], 255)
img = ~mask
# Detect corners (you can play with the parameters here)
dst = cv2.cornerHarris(img ,2,3,0.04)
dst = cv2.dilate(dst,None)
corners = dst > corners_threshold * dst.max()
# Draw lines to close the rooms off by adding a line between corners on the same x or y coordinate
# This gets some false positives.
# You could try to disallow drawing through other existing lines for example.
for y,row in enumerate(corners):
x_same_y = np.argwhere(row)
for x1, x2 in zip(x_same_y[:-1], x_same_y[1:]):
if x2[0] - x1[0] < room_closing_max_length:
color = 0
cv2.line(img, (x1, y), (x2, y), color, 1)
for x,col in enumerate(corners.T):
y_same_x = np.argwhere(col)
for y1, y2 in zip(y_same_x[:-1], y_same_x[1:]):
if y2[0] - y1[0] < room_closing_max_length:
color = 0
cv2.line(img, (x, y1), (x, y2), color, 1)
# Mark the outside of the house as black
contours, _ = cv2.findContours(~img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_sizes = [(cv2.contourArea(contour), contour) for contour in contours]
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
mask = np.zeros_like(mask)
cv2.fillPoly(mask, [biggest_contour], 255)
img[mask == 0] = 0
return biggest_contour, mask
#Read gray image
img = cv2.imread("/content/51626-7-floorplan-2.jpg", cv2.IMREAD_GRAYSCALE)
ext_contour, mask = find_rooms(img.copy())
cv2_imshow(mask)
print('exterior')
epsilon = 0.01*cv2.arcLength(ext_contour,True)
approx = cv2.approxPolyDP(ext_contour,epsilon,True)
final = cv2.drawContours(img, [approx], -1, (0, 255, 0), 2)
cv2_imshow(final)
这些平面图将仅具有两种形状中的一种,即 6 面形状和 4 面形状。下面是两种风格:
我需要忽略任何凸窗或小型挤压件。
我相信下一步是只有主墙的轮廓,使轮廓平滑,然后计算阵列中的边缘。我不知道如何做到这一点。任何帮助将不胜感激!
解决方案
简单的轮廓查找不太可能为您提供强大的解决方案。但是,您当前的方法可以通过首先计算白色背景的蒙版来改进。使用此蒙版的形状,您可以确定布局。
lower_color_bounds = cv.Scalar(255, 255, 255) upper_color_bounds = cv.Scalar(220, 220, 220)
mask = cv2.inRange(frame,lower_color_bounds,upper_color_bounds ) mask_rgb = cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)
推荐阅读
- android - 连接到运行多个启用 SSL 的 Web 应用程序的服务器时,Android websocket 客户端 SSL 错误
- c# - ML.Net 数组数据输入
- python - AttributeError:“模块”对象没有属性“DataFrame”
- git - 如何恢复尚未提交的 Git 更改?
- ansible - 获取本地主机上文件的绝对路径
- c++ - QtQuick 使用 QQuickTextNode
- java - 为request.setAttribute()发送多个属性
- c++ - 提升精神 x3 变体和 std::pair
- sql - 如何更改 Azure SQL 数据库中的用户角色?
- ios - 动态改变 UIPageControl.appearance 圆点的背景颜色