我想簡單地加載視頻文件,將其轉換爲灰度並顯示它。這裏是我的代碼: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()
這次視頻播放直到結束,窗口仍然凍結並在幾秒鐘後關閉。這一次我沒有得到任何錯誤。但爲什麼窗口會凍結?我該如何解決這個問題?
也許'cap.release()'需要一些時間才能完成。如果您最後交換了兩條線,窗口是否仍然凍結? – 2014-12-03 15:30:53
@Arnaud P是的 – Clive 2014-12-03 16:18:10
好的。作爲最終的猜測:如果你是多線程的,opencv圖像顯示不能在主線程上運行。 – 2014-12-03 17:23:30