cv2.VideoCapture(0).read() 返回(假,无)

Posted

技术标签:

【中文标题】cv2.VideoCapture(0).read() 返回(假,无)【英文标题】:cv2.VideoCapture(0).read() returns (False, None) 【发布时间】:2020-11-05 06:58:03 【问题描述】:
import cv2
cap=cv2.VideoCapture(0)
cap.set(3,640)#width
cap.set(4,480)#height
cap.set(10,100)#brightness
while True:
    success, img = cap.read()
    print(img)#getting None
    print(success)#getting False
    cv2.imshow("video", img)
    cv2.waitKey(1)
    if 0xFF == ord('q') :
        break

VideoCapture 可以很好地处理 mp4 视频。但是当我尝试将它用于我的笔记本电脑网络摄像头时,它不起作用。 第一次使用 pyCharm 在我的笔记本电脑上运行此代码。 起初,网络摄像头本身没有打开。所以,我签入here 并在 /Applications/PyCharm\ CE.app/Contents/Info.plist 中添加了以下内容

<key>Privacy - Camera Usage</key>
<string>An application in PyCharm wants to use the camera</string>

当我运行代码时网络摄像头启动后,imshow 却返回 None。

Traceback (most recent call last):
  File "/Users/sreeharsha/PycharmProjects/OpencvPython/chapter1.py", line 26, in <module>
    cv2.imshow("video", img)
cv2.error: OpenCV(4.4.0) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-4jcifzim/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

cap.isOpened() 返回 True 当我尝试 cap.getBackendName() 它返回以下错误

Traceback (most recent call last):
  File "/Users/sreeharsha/PycharmProjects/OpencvPython/chapter1.py", line 16, in <module>
    print(cap.getBackendName())
cv2.error: OpenCV(4.4.0) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-4jcifzim/opencv/modules/videoio/src/cap.cpp:299: error: (-215:Assertion failed) api != 0 in function 'getBackendName'

cv2.getBuildInformation()如下


General configuration for OpenCV 4.4.0 =====================================
  Version control:               4.4.0-dirty

  Platform:
    Timestamp:                   2020-09-22T21:19:42Z
    Host:                        Darwin 17.7.0 x86_64
    CMake:                       3.18.2
    CMake generator:             Unix Makefiles
    CMake build tool:            /usr/bin/make
    Configuration:               Release

  CPU/HW features:
    Baseline:                    SSE SSE2 SSE3 SSSE3 SSE4_1
      requested:                 DETECT
    Dispatched code generation:  SSE4_2 FP16 AVX AVX2 AVX512_SKX
      requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
      SSE4_2 (1 files):          + POPCNT SSE4_2
      FP16 (0 files):            + POPCNT SSE4_2 FP16 AVX
      AVX (4 files):             + POPCNT SSE4_2 AVX
      AVX2 (29 files):           + POPCNT SSE4_2 FP16 FMA3 AVX AVX2
      AVX512_SKX (4 files):      + POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX

  C/C++:
    Built as dynamic libs?:      NO
    C++ standard:                11
    C++ Compiler:                /usr/local/opt/ccache/libexec/clang++  (ver 9.1.0.9020039)
    C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    C Compiler:                  /usr/local/opt/ccache/libexec/clang
    C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    Linker flags (Release):      -Wl,-dead_strip  
    Linker flags (Debug):        -Wl,-dead_strip  
    ccache:                      YES
    Precompiled headers:         NO
    Extra dependencies:          -framework OpenCL /Applications/Xcode-9.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl ade Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Test Qt5::Concurrent openjp2
    3rdparty dependencies:       ittnotify libprotobuf zlib libjpeg-turbo libwebp libpng libtiff IlmImf quirc ippiw ippicv

  OpenCV modules:
    To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching video videoio
    Disabled:                    world
    Disabled by dependency:      -
    Unavailable:                 java js python2 ts
    Applications:                -
    Documentation:               NO
    Non-free algorithms:         NO

  GUI: 
    QT:                          YES (ver 5.13.2)
      QT OpenGL support:         NO
    Cocoa:                       YES
    VTK support:                 NO

  Media I/O: 
    ZLib:                        build (ver 1.2.11)
    JPEG:                        build-libjpeg-turbo (ver 2.0.5-62)
    WEBP:                        build (ver encoder: 0x020f)
    PNG:                         build (ver 1.6.37)
    TIFF:                        build (ver 42 - 4.0.10)
    JPEG 2000:                   OpenJPEG (ver 2.3.1)
    OpenEXR:                     build (ver 2.3.0)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      YES
      avcodec:                   YES (58.91.100)
      avformat:                  YES (58.45.100)
      avutil:                    YES (56.51.100)
      swscale:                   YES (5.7.100)
      avresample:                YES (4.0.0)
    GStreamer:                   NO
    AVFoundation:                YES

  Parallel framework:            GCD

  Trace:                         YES (with Intel ITT)

  Other third-party libraries:
    Intel IPP:                   2020.0.0 Gold [2020.0.0]
           at:                   /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-4jcifzim/_skbuild/macosx-10.13-x86_64-3.7/cmake-build/3rdparty/ippicv/ippicv_mac/icv
    Intel IPP IW:                sources (2020.0.0)
              at:                /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-4jcifzim/_skbuild/macosx-10.13-x86_64-3.7/cmake-build/3rdparty/ippicv/ippicv_mac/iw
    Lapack:                      YES (/Applications/Xcode-9.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
    Eigen:                       YES (ver 3.3.7)
    Custom HAL:                  NO
    Protobuf:                    build (3.5.1)

  OpenCL:                        YES (no extra features)
    Include path:                NO
    Link libraries:              -framework OpenCL

  Python 3:
    Interpreter:                 /Users/travis/build/skvark/opencv-python/venv/bin/python (ver 3.7.8)
    Libraries:                   /Library/Frameworks/Python.framework/Versions/3.7/lib/libpython3.7m.dylib (ver 3.7.8)
    numpy:                       /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-build-env-0spssg56/overlay/lib/python3.7/site-packages/numpy/core/include (ver 1.14.5)
    install path:                python

  Python (for build):            /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

  Java:                          
    ant:                         NO
    JNI:                         /Applications/Xcode-9.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/JavaVM.framework/Headers /Applications/Xcode-9.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/JavaVM.framework/Headers /Applications/Xcode-9.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/JavaVM.framework/Headers
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-4jcifzim/_skbuild/macosx-10.13-x86_64-3.7/cmake-install
-----------------------------------------------------------------

我也尝试使用各种 apiPreferences 创建 VideoCapture,但都失败了。

cap=cv2.VideoCapture(0, apiPreference=cv2.CAP_FFMPEG)

cap=cv2.VideoCapture(0, apiPreference=cv2.CAP_GSTREAMER)

cap=cv2.VideoCapture(0, apiPreference=cv2.CAP_V4L2)

请帮助我了解为什么会出现此问题以及如何解决此问题。

【问题讨论】:

【参考方案1】:

您还需要根据this 来检查帧是否被正确读取,尝试 vidcap,如下代码 sn-p:

import cv2
cap=cv2.VideoCapture(0, cv2.CAP_V4L)
cap.set(3,640)#width
cap.set(4,480)#height
cap.set(10,100)#brightness
while True:
    success, img = cap.read()
    if success:
        print(img)#getting None
        print(success)#getting False
        cv2.imshow("video", img)
        cv2.waitKey(1)
        if 0xFF == ord('q') :
            break

【讨论】:

我总是以 False 获得成功。所以,框架没有被正确读取。会是什么原因?

以上是关于cv2.VideoCapture(0).read() 返回(假,无)的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV VideoCapture解析

机器学习进阶-图像基本处理-视频的读取与处理 1.cv2.VideoCapture(视频的载入) 2.vc.isOpened(载入的视频是否可以打开) 3.vc.read(视频中一张图片的读取)

无法在 Android 手机中使用 cv2.VideoCapture(0) 打开相机

VideoCapture 似乎不适用于 Debian - opencv 3.2

Opencv python| cv. VideoCapture.get() 参数介绍

Python+opencv显示文字