【发布时间】:2020-03-25 16:32:12
【问题描述】:
我有一个包含多个房间的平面图。使用 Python,我想找到每个房间的中心并以 (x,y) 的形式存储坐标,以便我可以进一步使用它们进行数学计算。现有的drawContours 和FindContours 函数有助于确定轮廓,但是如何将获得的值存储到列表中。
该图片代表一个包含多个房间的示例平面图。
我尝试使用moments,但该功能无法正常工作。
As you may see this image is obtained from drawContours function. But then how do I store the x and y coordinates.
这是我的代码:
k= []
# Going through every contours found in the image.
for cnt in contours :
approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
# draws boundary of contours.
cv2.drawContours(img, [approx], -1, (0, 0,255), 3)
# Used to flatted the array containing
# the co-ordinates of the vertices.
n = approx.ravel()
i = 0
x=[]
y=[]
for j in n :
if(i % 2 == 0):
x = n[i]
y = n[i + 1]
# String containing the co-ordinates.
string = str(x) + " ," + str(y)
if(i == 0):
# text on topmost co-ordinate.
cv2.putText(img, string, (x, y),
font, 0.5, (255, 0, 0))
k.append(str((x, y)))
else:
# text on remaining co-ordinates.
cv2.putText(img, string, (x, y),
font, 0.5, (0, 255, 0))
k.append(str((x, y)))
i = i + 1
# Showing the final image.
cv2_imshow( img )
# Exiting the window if 'q' is pressed on the keyboard.
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
【问题讨论】:
-
你说时刻不起作用。但是你没有显示你的代码。请始终提供您的代码,以便其他人可以看到您是否有错误。一旦你有了轮廓,你就可以得到边界框,你可以从中轻松计算出中心。
-
暂时不,它给出了 ZeroDivisionError。这就是我没有包含它的原因
-
您仍然没有显示您的质心代码。给定有效轮廓,您应该能够从以下位置获取质心:` M = cv2.moments(cntr) cx = int(M["m10"] / M["m00"]) cy = int(M["m01" ] / M["m00"]) `
标签: python image opencv image-processing computer-vision