lj *_*j w 5 python opencv image-processing computer-vision opencv-contour
我想使用OpenCV和Python找到每个房间的精确轮廓数据,例如卧室和客厅,但做得不好。也许使用CNN?
我试图用cv2.erode,cv2.dilate和cv2.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)
Run Code Online (Sandbox Code Playgroud)
你“不能做得好”的部分到底是什么?我尝试了你的代码,绘制了房间中心的区域,看起来不错(除了一间卧室,其中不包括床)。这就是你的意思,还是你还没有走到这一步?
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)
Run Code Online (Sandbox Code Playgroud)