【问题标题】:OpenCV iterating through contoursOpenCV遍历轮廓
【发布时间】:2016-10-23 13:24:33
【问题描述】:

我正在尝试用一条线绘制图像中检测到的所有轮廓,我可以使用cnt = contour[number] 访问每个轮廓,但我似乎无法通过数组进行任何类型的迭代,总是得到任何一个

TypeError:只有一个元素的整数数组可以转换为索引

当我做for i in contours:

ValueError: 操作数太多

当我有下面的代码时

img, contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for i in np.nditer(contours):
    cnt = contours[i]

    rows,cols = img.shape[:2]
    [vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
    lefty = int((-x*vy/vx) + y)
    righty = int(((cols-x)*vy/vx)+y)
    img = cv2.line(im,(cols-1,righty),(0,lefty),(0,242,255),3)

cv2.imshow("line", img)

老实说,我对 OpenCV 和 numpy 非常陌生,并且一直在研究示例,但我对代码中的所有内容都不太了解,这让我很不满意。我认为这是我使用 numpy 数组的问题,但我似乎无法找到正确的方法。

谢谢

【问题讨论】:

  • 不会简单地for cnt in contours: 工作吗?
  • contours[i] 不能简单地将普通 i 作为一个整数工作,如果我不需要调用 contours[i] 它会工作。
  • 我认为默认情况下它具有单例暗淡。因此,当您需要使用contours[i] 时,请挤压它而不是np.squeeze(contours[i])
  • 我仍然收到操作数过多的错误
  • 我的意思是使用:for cnt in contours:。然后稍后在循环内部,使用np.squeeze(cnt) 而不是你有contours[i],但cv2.fitLine() 可能需要cnt,因为它没有挤压。

标签: python arrays opencv numpy opencv3.0


【解决方案1】:

你可以这样做

# loop over the contours
for c in contours:
    # get bounding rect
   (x,y,w,h) = cv2.boundingRect(c)
    # draw red rect
    cv2.rectangle(img, (x,y), (x+w,y+h), (0, 0, 255), 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2017-05-15
    • 2021-09-14
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多