Python, OpenCv数组错误
我正在尝试用Python和cv2库在图像中绘制运动的轮廓。为了实现运动检测,我参考了这个教程:http://www.steinm.com/blog/motion-detection-webcam-python-opencv-differential-images/,但是在尝试不同的方法绘制轮廓时,总是遇到各种数组错误。
我的方法是这样的:我先找到差异图像,然后在这个图像上找到轮廓。接着,我在差异图像上绘制轮廓,然后显示出来。
这是我的代码:
import cv2
import numpy as np
#Find the differential image
def diffImg(t0, t1,t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
d_final = cv2.bitwise_and(d1,d2)
d_binary = cv2.threshold(d_final, 35, 255,cv2.THRESH_BINARY)[1]
d_blur = cv2.blur(d_binary, (15,15))
return d_blur
#Capture Video from camera
cam = cv2.VideoCapture(0)
s, img = cam.read()
window_name = "Movement Visual"
cv2.namedWindow(window_name, cv2.CV_WINDOW_AUTOSIZE)
#Read the first three images to find the differential image
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
while s:
#draw contours
contours, hierarchy = cv2.findContours(diffImg(t_minus,t,t_plus),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
final_contour = cv2.drawContours(img,contours,-1,(250,250,250),2)
cv2.imshow(window_name,final_contour)
t_minus = t
t = t_plus
t_plus = cv2.cvtColor(cam.read()[1],cv2.COLOR_RGB2GRAY)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(window_name)
break
print "Bye"
#cv2.imwrite("image.png", diffImg(t_minus,t,t_plus)
这是我遇到的错误:
line 28, in <module>
cv2.imshow(window_name,final_contour)
error: C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array.cpp:2482: error: (-206) Unrecognized or unsupported array type
在第28行,我在循环中声明了final_contour。我不明白为什么会出现这个错误,因为看起来我只是把图像在函数之间进行了交换。
谢谢任何建议。
1 个回答
1
好的,我搞明白了,感谢@Constantine提醒我检查我的代码。当我打印出 diffImg(t_minus,t,t_plus)
、contour
和 hierarchy
的值时,我发现它们分别是一个全是零的数组、空数组和 None。所以,至少在我看来,根本没有可以绘制轮廓的图像。这就是出错的原因。我把代码改成在直接从相机读取的彩色图像的副本上绘制轮廓。简单来说,我先在 diffImg(t_minus,t,t_plus)
上找到轮廓,然后再把这些轮廓绘制到相机的图像上,并在新屏幕上显示出来。下面是代码的一部分,帮助你理解:
while s:
#draw contours
contours, hierarchy = cv2.findContours(diffImg(t_minus,t,t_plus),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,contours,-1,(250,250,250),2)
cv2.imshow('Contours',img)
cv2.imshow(window_name,diffImg(t_minus,t,t_plus))
t_minus = t
t = t_plus
t_plus = cv2.cvtColor(cam.read()[1],cv2.COLOR_RGB2GRAY)
...