【问题标题】:Opencv TypeError: points is not a numpy array, neither a scalarOpencv TypeError:点不是一个numpy数组,也不是一个标量
【发布时间】:2014-05-30 07:44:07
【问题描述】:

基本上,我有这段代码可以检测背景变化并将它们装箱。当我运行代码时,我得到这个错误:

Traceback (most recent call last):
  File "cam2.py", line 28, in <module>
    vertices = cv2.boundingRect(list(contours))
TypeError: points is not a numpy array, neither a scalar

代码:

import cv2
import numpy as np

c = cv2.VideoCapture(0)
_,f = c.read()

avg1 = np.float32(f)

while(1):
    _,f = c.read()

    cv2.accumulateWeighted(f,avg1,0.1)

    res1 = cv2.convertScaleAbs(avg1)

    absdiff = cv2.absdiff(f,res1)

    graydiff = cv2.cvtColor(absdiff, cv2.COLOR_BGR2GRAY)

    retval, mask = cv2.threshold(graydiff, 50,255,cv2.THRESH_BINARY) 

    mask = cv2.dilate(mask, None, 18)
    mask = cv2.erode(mask, None, 10) 

    contours = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) #not right

    while contours:
        vertices = cv2.boundingRect(list(contours))
        interest = vertices

        point1 = (interest[0], interest[1])

        point2 = (interest[0] + interest[2], interest[1] + interest[3])
        cv2.rectangle(f, point1, point2, cv2.RGB(255,0,0), 1)
        cv2.rectangle(mask, point1, point2, cv2.RGB(255,255,255), 1)

        contours = contours.h_next()

    cv2.imshow('mask',mask)

    cv2.imshow('img',f)
    cv2.imshow('avg1',res1)

    k = cv2.waitKey(20)

    if k == 27:
        break

cv2.destroyAllWindows()
c.release()

我该如何解决这个问题?谢谢。

【问题讨论】:

  • 你跟踪你的代码了吗!? contours 列表的值是多少?
  • 该值是一个很长的数组,这里有一个 sn-p:[[ 995, 1018]], [[ 995, 1019]], [[ 995, 1020]], [[ 995, 1021 ]],
  • 看起来你有 4 个轮廓,每个轮廓只包含一个点!?
  • 那么如何获得多个积分呢?
  • 你能分享你的图片吗?

标签: python opencv


【解决方案1】:

根据findContour 文档,它返回两件事:

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → contours, hierarchy

将行改为:

contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) 

这可能行得通!

【讨论】:

  • 啊 ofc。 ,错过了。
【解决方案2】:

contours 实际上是一个双数组。外层是轮廓列表,内层是单个轮廓的点。

所以,替换:

while contours:
    vertices = cv2.boundingRect(list(contours))

与:

for cnt in contours:
    vertices = cv2.boundingRect(cnt)

然后放下

contours = contours.h_next()

行(您可能会将 cv2 与旧的 c-api/cv 方法混淆,后者在底层使用链表)

【讨论】:

  • 嗯...仍然无法正常工作(同样的错误)。但是谢谢你告诉我最后的评论。
  • 你现在可能犯了另一个错误。
  • 我希望 :( TypeError: points 不是一个 numpy 数组,也不是一个标量
猜你喜欢
  • 2013-07-11
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多