【问题标题】:OpenCV returns an Array of All Zeros on video.readOpenCV 在 vi​​deo.read 上返回一个全零数组
【发布时间】:2019-08-11 16:31:57
【问题描述】:

下面是相关代码

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

编辑:Frame 不为空,但数组中的所有值似乎都是 '0'

为什么框架是空的,如何让 OpenCV 在框架中检测到我的脸?

【问题讨论】:

  • 我建议改写你的问题——全零不是一个空框架,而是一个完全黑的框架。 “空”帧更类似于为您的frame 获取None,而不是黑色图像。你每帧都得到这个吗?您如何打开视频捕获设备?您已将那部分代码遗漏了。
  • @AlexanderReynolds 第一部分是正确的,我将改写它。但这是我为这个项目编写的代码的范围。我不太了解后端发生了什么。
  • 抱歉,您的代码部分滚动了 3 行,我没有意识到它滚动了,以为您遗漏了顶部。您确定0 对应于您的网络摄像头吗?如果您有多个摄像头连接到您的计算机,它可能是12...等。否则,请确保您可以在 OpenCV 之外的计算机上获取网络摄像头源,并且它看起来正确。如果一切正常但 OpenCV 只有黑色图像,我会考虑重新安装 OpenCV,如果可能的话从源代码构建。
  • @AlexanderReynolds 我认为确实如此,因为当我运行我的代码时,它会打开内置摄像头的正面。

标签: python python-3.x opencv ffmpeg


【解决方案1】:

有时图片无法读取,所以 cv2 返回一个空矩阵,需要确保帧不为空。

...
while True:
    a += 1
    check, frame = video.read()
    if not check or frame.empty():
        continue
    ...

【讨论】:

  • 图片好像无法读取。我不确定这是为什么。
  • 你只得到空帧吗?
  • 是的,我只得到那些空帧。@Alakazam
【解决方案2】:

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

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

我找到了答案here

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

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

documentation中有一个例子

【讨论】:

  • 你能在你的答案中添加一些解释吗?
  • 根据文档 cv2.CAP_DSHOW 指的是 Direct Show,它是一个多媒体框架和 API,用于对媒体文件或流执行各种操作。
【解决方案3】:

确保您能够连接到相机

...
while True:
    a = a + 1
    if video.isOpened():
        check, frame = video.read()
        print(frame)
    ...

【讨论】:

  • 我可以连接到相机,只是似乎没有读取帧
【解决方案4】:

我认为这是由于防病毒软件。尝试禁用它。

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2020-11-16
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多