Opencv TypeError:points不是一个numpy数组,也不是标量

时间:2014-04-15 19:14:45

标签: python opencv

基本上,我有这个代码可以检测后台的变化并将它们装箱。当我运行代码时,我收到此错误:

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()

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

2 个答案:

答案 0 :(得分:4)

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

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

将行更改为:

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

那可能有用!

答案 1 :(得分:1)

轮廓实际上是一个双阵列。外部轮廓是轮廓列表,内部轮廓是单个轮廓的点。

所以,替换:

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

使用:

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

并删除

contours = contours.h_next()

行(您可能将cv2与旧的c-api / cv方法混淆,后者在引擎盖下使用链接列表)