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

How to draw lines between points in 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) 

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

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) 

如果只是想画线,cv2.polylines怎么样? cv2.drawContours 如果您已经有一个等高线对象,那将是首选。

cv2.polylines(image, 
              a, 
              isClosed = False,
              color = (0,255,0),
              thickness = 3, 
              linetype = cv2.LINE_AA)