cv2.error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:25

cv2.error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:253

最近刚开始学习python,涉及到了OpenCV模块,运行一个书上的程序出错了,原程序如下:


import cv2
import numpy as np
cap = cv2.VideoCapture('1.mp4')
while True:
    # 获取每一帧
    ret, frame = cap.read()

    # 转换到 HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # 设定蓝色的阈值
    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([130, 255, 255])

    # 根据阈值构建掩模
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # 对原图像和掩模进行位运算
    res = cv2.bitwise_and(frame, frame, mask=mask)

    # 显示图像
    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
# 关闭窗口
cv2.destroyAllWindows()

错误信息如下:

E:\python3.7.8\python.exe E:/1/PycharmProjects/opencv_test/color_transfer.py
Traceback (most recent call last):
File "E:/1/PycharmProjects/opencv_test/color_transfer.py", line 29, in <module>
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
cv2.error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper,struct cv::Set<3,-1,-1>,struct cv::Set<0,5,-1>,2>::CvtHelper'

Process finished with exit code 1

  1. 根据错误提示,是cv2.cvtColor函数的第一个参数frame出错了,其他的我看不出来了。
  2. 我返回检查了我的mp4文件以及调用的文件路径,没有问题。
  3. 再次运行程序,这次不等视频自己放完就按下Esc键结束,然后没有出现错误提示信息。
  4. 所以,说明是frame在循环过程中出错了。
    将程序简化,单独测试下循环和frame,程序和错误信息分别如下:
import cv2
cap = cv2.VideoCapture('1.mp4')
while True:
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()

E:\python3.7.8\python.exe E:/1/PycharmProjects/opencv_test/test.py
Traceback (most recent call last):
  File "E:/1/PycharmProjects/opencv_test/test.py", line 9, in <module>
    cv2.imshow('frame', frame)
cv2.error: OpenCV(3.4.2) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

Process finished with exit code 1

从错误信息可以看出,程序中frame最后没有满足imshow函数要求的size.width>0 && size.height>0,此时打印frame的值,发现frame是空的,我才突然恍然大悟,
猜测错误来源:while一直在循环,视频放完了它继续循环,frame获得值就是空的,而imshow和cv2.cvtColor函数引用到了空值,造成了参数的错误引用 ,然后程序非正常结束。
解决方法:控制frame的值,当frame为空时结束循环。在程序中while循环内frame下面加入如下if语句:

    if frame is None:
        break

检验结果

E:\python3.7.8\python.exe E:/1/PycharmProjects/opencv_test/test.py
Process finished with exit code 0
E:\python3.7.8\python.exe E:/1/PycharmProjects/opencv_test/color_transfer.py
Process finished with exit code 0

你可能感兴趣的:(笔记,python,opencv)