首页 > 解决方案 > OpenCV 在 vi​​deo.read 上返回一个全零数组

问题描述

下面是相关代码

import cv2 as cv
import numpy as np

video = cv.VideoCapture(0) #tells obj to use built in camera\

#create a face cascade object 
face_cascade  = 
cv.CascadeClassifier(r"C:\Users\xxxxxxx\AppData\Roaming\Python\Python36\site- 
packages\cv2\data\haarcascade_frontalcatface.xml")

a = 1
#create loop to display a video
while True:
    a = a + 1
    check, frame = video.read()
    print(frame)

    #converts to a gray scale img
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    #create the faces
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)

    for(x, y, w, h) in faces:
        print(x, y, w, h)

    #show the image
    cv.imshow('capturing', gray)

    key = cv.waitKey(1) #gen a new frame every 1ms

    if key == ord('q'): #once you enter 'q' the loop will be exited
        break

print(a) #this will print the number of frames

#captures the first frame
video.release() #end the web cam

#destroys the windows when you are not defined
cv.destroyAllWindows()

该代码显示从我的网络摄像头捕获的视频。尽管如此,OpevCV 似乎并没有处理任何帧,因为所有帧看起来都像这样

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]]

我认为这意味着它们是空的。

我相信这会阻止算法在框架中检测到我的脸。我觉得问题出在 ffmpeg 编解码器上,但即使是这种情况,我也不完全确定如何进行。

操作系统:Windows 10 语言:Python

编辑:框架不为空,但数组中的所有值似乎都是“0”

为什么框架是空的,我怎样才能让 OpenCV 在框架中检测到我的脸?

标签: pythonpython-3.xopencvffmpeg

解决方案


如果您使用的是 Windows 似乎会发生这种情况
我在收到此警告后提出了解决方案

[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback

我在这里找到了答案

video = cv.VideoCapture(0, cv2.CAP_DSHOW)

根据文档 cv2.CAP_DSHOW 指的是 Direct Show,它是一个多媒体框架和 API,用于对媒体文件或流执行各种操作。

文档中有一个示例


推荐阅读