2014-12-02 67 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

相关问题