2015-05-23 125 views
0

我正在使用Raspberry Pi,官方Raspberry Pi Camera和OpenCV用Python編程移動偵測系統。雖然我使用的absdiff和bitwise_and操作談到了這一點:覆盆子pi相機移動偵測

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp, line 3739 Traceback (most recent call last): File "icanseeu-diff.py", line 18, in t_minus = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) cv2.error: /home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp:3739: error: (-215) scn == 3 || scn == 4 in function cvtColor

下面是代碼:

import cv2 
from picamera.array import PiRGBArray 
from picamera import PiCamera 
import time 

camera = PiCamera() 
camera.resolution = (320, 240) 
camera.framerate = 30 
camera.rotation = 180 
rawCapture = PiRGBArray(camera, size = (320, 240)) 

def diffImg(t0, t1, t2): 
    d1 = cv2.absdiff(t2, t1) 
    d2 = cv2.absdiff(t1, t0) 
    return cv2.bitwise_and(d1, d2) 

# Read three images first 
frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) 
frame2 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) 
frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) 

while True: 
    cv2.imshow(motions, diffImg(t_minus, t, t_plus)) 

    # Read next image 
    frame1 = frame2 
    frame2 = frame3 
    frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) 

    key = cv2.waitKey(10) 
    if key == 27: 
     cv2.destroyWindow(motions) 
     break 

似乎是一個分配的問題,但我不知道該如何處理用它。我該怎麼辦?謝謝!

+0

您的'PiRGBArray'是否設計爲採用'rgb'圖像,您不應該使用'rgb'格式而不是'bgr'來捕獲圖像嗎? – mpursuit

回答

0

爲了節省您的時間,我構建了一個完整的應用程序來檢測動作並通知iOS/Android。通知將包含文字,圖片和視頻。 Check this out

0

您收到的錯誤消息是通知您傳遞的圖像沒有3或4個通道。這是失敗的評估。

這是因爲camera.capture函數不返回任何值(API Documentation)。相反rawCapture得到更新,這是你應該傳遞到cvtColor

而不是

frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) 

使用

rawCapture.truncate() 
camera.capture(rawCapture, format = "bgr", use_video_port = True) 
frame1 = cv2.cvtColor(rawCapture.array, cv2.COLOR_BGR2GRAY) 

而同樣的每次拍攝圖像的時間。

我還沒有能夠測試這個,因爲我目前沒有我的樹莓派和相機,但它應該解決這個問題。

+0

謝謝,這個錯誤不會再出現,但現在它出來與此控制檯日誌: '回溯(最近通話最後一個): 文件「icanseeu-diff.py」 19行,在 幀1 = cv2.cvtColor(rawCapture,cv2.COLOR_RGB2GRAY) TypeError:src不是一個numpy數組,不是一個標量' 我應該如何將rawCapture轉換爲一個numpy數組? – Laeknishendr

+0

[PiCamera.PiRGBArray](https://picamera.readthedocs.org/en/release-1.10/api_array.html)上的文檔建議您可以使用'PiRGBArray'上的'array'屬性來獲得一個numpy數組這是'cvtColor'工作所需要的。 我修改了更新後的代碼的答案。請注意,捕獲的格式需要爲「bgr」,因爲這是openCV預期的格式。另外,在捕獲每個圖像之前需要調用truncate()來刪除以前的內容。 – mpursuit

0

我認爲你沒有關閉你的相機,所以python認爲相機被另一個程序使用。嘗試重新啓動你的Pi。該程序應該在重新啓動後工作。重新啓動後程序的第二次啓動將不起作用。如果發生這種情況,請關閉最後一條if語句中的相機。