cvtColor函数中的openCV错误:断言失败(scn == 3 || scn == 4)

时间:2014-12-02 11:17:02

标签: python opencv

我想简单地加载一个视频文件,将其转换为灰度并显示它。这是我的代码:

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

我取消注释了print frame.shape语句。它保持打印7​​20,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()

这次视频播放到最后,窗口仍然会在几秒钟后冻结并关闭。这次我没有收到任何错误。但为什么窗户会冻结?我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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