打开cv错误:-215scn == 3 ||函数cvtColor中的scn == 4:Google Colab

问题描述

当我在colab中尝试以下代码时,我没有得到任何错误,也没有得到任何输出。我也尝试过javascript访问网络摄像头。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret,frame = cap.read()

    # 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()

解决方法

here中所述,很有可能ret值返回false。结果,该程序无法获取帧。

  • 选项1:请确保您以管理员权限运行代码,因为该程序可能无法访问相机。

  • 选项2:在将框架转换为灰度之前,可以使用if ret==True:语句。

    例如:

    while(True):
        ret,frame = cap.read()
        if ret:
            gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
            # Rest of the code ..