【问题标题】:How to draw lines between points in OpenCV?如何在 OpenCV 中的点之间画线?
【发布时间】:2018-06-03 22:25:39
【问题描述】:

我有一个元组数组:

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) 

【问题讨论】:

  • 官方文档中有绘图教程。 docs.opencv.org/3.1.0/dc/da5/tutorial_py_drawing_functions.html - 到目前为止你尝试过什么?
  • 我知道,但是教程告诉使用两点:cv2.line(img,(0,0),(511,511),(255,0,0),5),但我有一些点
  • 您还可以使用点列表绘制多边形或轮廓。你到底想达到什么目标?
  • 请显示您的一些代码。如果您还没有任何编码,则很难满足 Stack Overflow 要求问题具体化的要求。
  • pointsInside =[] for index, item in enumerate(pointsInside): print (item[index]) #cv2.line(image, item[index], item[index + 1], [0, 255, 0], 2)

标签: python opencv opencv3.0 opencv-contour


【解决方案1】:

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

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) 

【讨论】:

【解决方案2】:

如果你只是想画线,cv2.polylines呢? cv2.drawContours 当你已经有一个轮廓对象时会更好。

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

【讨论】:

  • 我发布的 cv2.drawContours(img, [a], 0, (255,255,255), 2) 也是一行,但我认为您的解决方案非常合适。
  • @Zev:我的错。我没有仔细阅读您的代码。 cv2.drawContours 可能也一样好,特别是如果您已经有一个轮廓对象可以使用。
  • 太棒了。不关闭线条及其无环
  • 这对我有用 cv2.polylines(image, [np.array(a)], isClosed = False, color = (0,255,0), thickness = 3, linetype = cv2.LINE_AA) a = [(375, 193) (364, 113) (277, 20) (271, 16) (52, 106) (133, 266) (289, 296) (372, 282)]
  • 绘制轮廓后,如何获取所有轮廓并存储它们,您刚刚绘制的内容,同时忽略图像中的其他所有内容?
猜你喜欢
  • 2014-03-01
  • 2014-01-03
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2022-01-07
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多