2014-12-02 119 views
3

我想簡單地加載視頻文件,將其轉換爲灰度並顯示它。這裏是我的代碼:cVtColor函數中的openCV錯誤:聲明失敗(scn == 3 || scn == 4)

import numpy as np 
import cv2 

cap = cv2.VideoCapture('cars.mp4') 

while(cap.isOpened()): 
    # Capture frame-by-frame 
    ret, frame = cap.read() 
    #print frame.shape 


    # Our operations on the frame come here 
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

    # Display the resulting frame 
    cv2.imshow('frame',gray) 
    if cv2.waitKey(1) & 0xFF == ord('q'): 
     break 


# When everything done, release the capture 
cap.release() 
cv2.destroyAllWindows() 

視頻播放灰度直到結束。然後它凍結和窗口變得不響應,我得到以下錯誤在終端:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/clive/Downloads/OpenCV/opencv-2.4.9/modules/imgproc/src/color.cpp, line 3737 
Traceback (most recent call last): 
    File "cap.py", line 13, in <module> 
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
cv2.error: /home/clive/Downloads/OpenCV/opencv-2.4.9/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor 

我註釋掉的語句打印frame.shape。它不斷打印720,1028,3。但視頻播放,直到結束後,凍結,一段時間後,關閉並返回

print frame.shape 
AttributeError: 'NoneType' object has no attribute 'shape' 

據我所知,這個斷言失敗按摩通常意味着我想轉換一個空的圖像。在使用if(ret):語句開始處理之前,我添加了對空圖像的檢查。 (任何其他方式?)

import numpy as np 
import cv2 

cap = cv2.VideoCapture('cars.mp4') 

while(cap.isOpened()): 
    # Capture frame-by-frame 
    ret, frame = cap.read() 
    #print frame.shape 

    if(ret): #if cam read is successfull 
     # Our operations on the frame come here 
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

     # Display the resulting frame 
     cv2.imshow('frame',gray) 
     if cv2.waitKey(1) & 0xFF == ord('q'): 
      break 
    else: 
     break 

# When everything done, release the capture 
cap.release() 
cv2.destroyAllWindows() 

這次視頻播放直到結束,窗口仍然凍結並在幾秒鐘後關閉。這一次我沒有得到任何錯誤。但爲什麼窗口會凍結?我該如何解決這個問題?

+0

也許'cap.release()'需要一些時間才能完成。如果您最後交換了兩條線,窗口是否仍然凍結? – 2014-12-03 15:30:53

+0

@Arnaud P是的 – Clive 2014-12-03 16:18:10

+0

好的。作爲最終的猜測:如果你是多線程的,opencv圖像顯示不能在主線程上運行。 – 2014-12-03 17:23:30

回答

1

的waitKey()部分不應該依賴於框架的有效性,將其移出的條件:

import numpy as np 
import cv2 

cap = cv2.VideoCapture('cars.mp4') 

while(cap.isOpened()): 
    # Capture frame-by-frame 
    ret, frame = cap.read() 
    #print frame.shape 

    if(ret): #if cam read is successfull 
     # Our operations on the frame come here 
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

     # Display the resulting frame 
     cv2.imshow('frame',gray) 
    else: 
     break 

    # this should be called always, frame or not. 
    if cv2.waitKey(1) & 0xFF == ord('q'): 
     break 
+0

我嘗試了你的建議,但仍得到相同的結果。視頻結束後窗口凍結。 – Clive 2014-12-03 16:19:01

+0

我注意到,如果「else」語句放在最後一個「if」語句之後,那麼視頻根本不播放。我只是看到窗口彈出並顯示框架並迅速關閉。它發生得很快。我猜只有一個幀被播放。這是爲什麼? – Clive 2014-12-03 16:21:04

+0

因爲你的代碼然後說'如果q':break else:break'這意味着它根本無法循環。 – 2014-12-03 17:26:12