首页 > 解决方案 > 如何使用 OpenCV 或深度学习从平面图中扫描房间轮廓数据?

问题描述

我想找到每个房间的准确轮廓数据,例如卧室和客厅,使用OpenCV和Python,但做不好。也许使用CNN?

我尝试使用cv2.erode,cv2.dilatecv2.findContours.

这是一个扫描平面图的示例: 在此处输入图像描述 我真的希望结果包含特殊房间的所有空间,包括家具,但不能包含其他房间的空间,例如卧室不能包含客厅的空间,并且轮廓不能包含曲线。我只是这样: 在此处输入图像描述

这是我的python代码:

import cv2
import random
img = cv2.imread('./lj_hx/zz.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

cv2.imshow("thresh", thresh)

mor_img = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (5, 5), iterations=3)

_, contours, _ = cv2.findContours(mor_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

for c in sorted_contours[1:]:
    area = cv2.contourArea(c)
    if area > 6000:
        cv2.drawContours(img, [c], -1, (random.randrange(0, 255), random.randrange(0, 256), random.randrange(0, 255)), 3)

cv2.imshow("mor_img", mor_img)
cv2.imshow("img", img)

cv2.waitKey(0)

标签: pythonopencvimage-processingcomputer-visionopencv-contour

解决方案


你“不能做好[...]”的部分到底是什么?我尝试了您的代码,绘制了房间中心的区域,看起来不错(除了 1 间卧室,其中不包括床)。这是你的意思,还是你没有走到这一步?

import cv2
import random
img = cv2.imread('./lj_hx/zz.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

cv2.imshow("thresh", thresh)

mor_img = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (3, 3), iterations=3)

contours, hierarchy = cv2.findContours(mor_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # I addapted this part of the code. This is how my version works (2.4.16), but it could be different for OpenCV 3 

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

for c in sorted_contours[1:]:
    area = cv2.contourArea(c)
    if area > 6000:
        print area
        cv2.drawContours(img, [c], -1, (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)), 3)
        x, y, w, h = cv2.boundingRect(c) # the lines below are for getting the approximate center of the rooms
        cx = x + w / 2
        cy = y + h / 2
        cv2.putText(img,str(area),(cx,cy), cv2.FONT_HERSHEY_SIMPLEX, .5,(255,0,0),1,cv2.CV_AA)

cv2.imshow("mor_img", mor_img)
cv2.imshow("img", img)
cv2.waitKey(0)

推荐阅读