首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >cvtColor函数中出现openCV错误:断言失败(scn == 3 || scn == 4)

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

Stack Overflow用户
提问于 2014-12-02 19:17:02
回答 1查看 4.6K关注 0票数 3

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

代码语言:javascript
运行
复制
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()

这个视频一直播放到最后。然后它冻结,窗口变得没有响应,我在终端中得到以下错误:

代码语言:javascript
运行
复制
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的注释。它一直在打印720,1028,3。但在视频播放到结束后,它会冻结,一段时间后它会关闭并返回

代码语言:javascript
运行
复制
print frame.shape   
AttributeError: 'NoneType' object has no attribute 'shape'

我知道这个断言失败消息通常意味着我正在尝试转换一个空图像。在开始使用if(ret):语句处理图像之前,我添加了对空图像的检查。(有没有其他方法??)

代码语言:javascript
运行
复制
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()

这一次,视频一直播放到最后,窗口仍然冻结并在几秒钟后关闭。这一次,我没有得到任何错误。但是为什么窗口会冻结呢?我怎么才能修复它呢?

EN

回答 1

Stack Overflow用户

发布于 2014-12-02 19:40:57

waitKey()部分不应依赖于帧的有效性,请将其移出条件:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27248068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档