首页 > 解决方案 > 如何在 OpenCV 中的点之间画线?

问题描述

我有一个元组数组:

a = [(375, 193)
(364, 113)
(277, 20)
(271, 16)
(52, 106)
(133, 266)
(289, 296)
(372, 282)]

如何在 OpenCV 中的点之间画线?

这是我的代码不起作用:

for index, item in enumerate(a): 
    print (item[index]) 
    #cv2.line(image, item[index], item[index + 1], [0, 255, 0], 2) 

标签: pythonopencvopencv3.0opencv-contour

解决方案


使用绘制轮廓,您可以一次绘制所有形状。

img = np.zeros([512, 512, 3],np.uint8)
a = np.array([(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)])
cv2.drawContours(img, [a], 0, (255,255,255), 2)

如果您不想关闭图像并希望继续您的开始方式:

image = np.zeros([512, 512, 3],np.uint8)
pointsInside = [(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)]

for index, item in enumerate(pointsInside): 
    if index == len(pointsInside) -1:
        break
    cv2.line(image, item, pointsInside[index + 1], [0, 255, 0], 2) 

关于您当前的代码,您似乎正试图通过索引当前点来访问下一个点。您需要检查原始数组中的下一个点。

执行第二个版本的更 Pythonic 方式是:

for point1, point2 in zip(a, a[1:]): 
    cv2.line(image, point1, point2, [0, 255, 0], 2) 

推荐阅读