2014-04-14 37 views
0

我想繪製輪廓,我看到使用python和cv2的圖像中的運動。 我遵循這裏的教程:http://www.steinm.com/blog/motion-detection-webcam-python-opencv-differential-images/以獲得運動部分的工作,但當我嘗試使用不同的方法來繪製輪廓時,我仍然遇到不同的陣列錯誤。Python,OpenCv數組錯誤

這是我的方法。我找到差分圖像,然後找到該圖像上的輪廓。然後我在差分圖像上繪製輪廓,然後顯示它。

下面是代碼:

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) 

這裏是我得到的錯誤:其中final_contour在while循環聲明

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。我不明白爲什麼我得到這個,因爲它看起來像我基本上只是交換函數之間的圖像。

感謝您的任何建議。

+1

你跟蹤你的代碼!? 'final_contour'的類型是什麼? – Hadi

+1

是的。我可以打印出尺寸。我相信等值線是作爲一個列表出現的,但是在我看到final_contour是什麼之前它就失敗了。 – JustBlossom

回答

1

好吧所以,想出了道具@Constantine提醒我跟蹤我的代碼。當我打印出什麼diffImg(t_minus,t,t_plus)contourhierarchy,我發現他們是一個零數組,分別爲[]和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) 
    ...