You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开机启动OpenCV读取RTSP流遇CAP_IMAGES找不到起始编号错误求助

问题:开机启动时OpenCV无法读取海康威视RTSP流

环境信息

  • OpenCV-Python 4.7.0
  • Python 3.10.10
  • 海康威视IP摄像头(RTSP流)

现象

手动执行Python脚本时可正常读取RTSP流,但将脚本快捷方式放入开机启动文件夹后,流媒体功能失败,报错如下:

[ERROR: 0@90.973] global cap.cpp:166 cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception
OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_images.cpp: 253: error: (-5: Bad argument) CAP_IMAGES: Can't find the starting number (in the name of file): rtsp://admin: xxxx@xxxxxxxx:554/Streaming/Channels/101/ in the function 'cv::icvExtractPattern'

相关代码

核心使用grabImage()函数,完整类代码:

class VideoStreamWidget(object):
    def __init__(self, src='rtsp://admin:xxxxxx@xxx.xxx.xx.xxx:554/Streaming/Channels/101/',valve=cv2.CAP_FFMPEG):
        # Create a VideoCapture object
        # Error in the line below
        self.capture = cv2.VideoCapture(src)

        print(valve)
        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()
        print("Thread started")
        
    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            self.frame = self.maintain_aspect_ratio_resize(self.frame, width=600)
            cv2.imshow('IP Camera Video Streaming', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            cv2.destroyAllWindows()
            exit(1)
        
        if key%256 == 27:
            # ESC pressed
            print("Escape hit, closing...")
            #break

        img_counter = 0   
        if key%256 == 32:
            # SPACE pressed
            img_name = "opencv_frame_{}.png".format(img_counter)
            cv2.imwrite(img_name, self.frame)
            print("{} written!".format(img_name))
            img_counter += 1

    def grabImage(self, image_name = 'Image'):
         
        # time_diff = (self.end_time - datetime.now())
        
        
        # frame_time = 1000*time_diff.total_seconds()#round(1000*time_diff.total_seconds()/0)*40
        # print('frame_time',frame_time)
        
        if self.status:
            cv2.imwrite("files/image/staging/"+image_name+".jpg", self.frame)     # save frame as JPEG file
        else:
            print('No images is collected on the frame') 

    # Resizes a image and maintains aspect ratio
    def maintain_aspect_ratio_resize(self, image, width=None, height=None, inter=cv2.INTER_AREA):
        # Grab the image size and initialize dimensions
        dim = None
        (h, w) = image.shape[:2]

        # Return original image if no need to resize
        if width is None and height is None:
            return image

        # We are resizing height if width is none
        if width is None:
            # Calculate the ratio of the height and construct the dimensions
            r = height / float(h)
            dim = (int(w * r), height)
        # We are resizing width if height is none
        else:
            # Calculate the ratio of the width and construct the dimensions
            r = width / float(w)
            dim = (width, int(h * r))

        # Return the resized image
        return cv2.resize(image, dim, interpolation=inter)

OpenCV构建信息

General configuration for OpenCV 4.7.0 =====================================
  Version control:               4.7.0

  Platform:
    Timestamp:                   2023-02-22T13:19:52Z
    Host:                        Windows 10.0.17763 AMD64
    CMake:                       3.24.2
    CMake generator:             Visual Studio 14 2015
    CMake build tool:            MSBuild.exe
    MSVC:                        1900
    Configuration:               Debug Release

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

  C/C++:
    Built as dynamic libs?:      NO
    C++ standard:                11
    C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe  (ver 19.0.24245.0)
    C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MP  /MT /O2 /Ob2 /DNDEBUG
    C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MP  /MTd /Zi /Ob0 /Od /RTC1
    C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
    C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /MP   /MT /O2 /Ob2 /DNDEBUG
    C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /MP /MTd /Zi /Ob0 /Od /RTC1
    Linker flags (Release):      /machine:x64  /NODEFAULTLIB:atlthunk.lib /INCREMENTAL:NO  /NODEFAULTLIB:libcmtd.lib /NODEFAULTLIB:libcpmtd.lib /NODEFAULTLIB:msvcrtd.lib
    Linker flags (Debug):        /machine:x64  /NODEFAULTLIB:atlthunk.lib /debug /INCREMENTAL  /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libcpmt.lib /NODEFAULTLIB:msvcrt.lib
    ccache:                      NO
    Precompiled headers:         YES
    Extra dependencies:          wsock32 comctl32 gdi32 ole32 setupapi ws2_32
    3rdparty dependencies:       libprotobuf ade ittnotify libjpeg-turbo libwebp libpng libtiff libopenjp2 IlmImf zlib 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 python2 ts
    Applications:                -
    Documentation:               NO
    Non-free algorithms:         NO

  Windows RT support:            NO

  GUI:                           WIN32UI
    Win32 UI:                    YES
    VTK support:                 NO

  Media I/O:
    ZLib:                        build (ver 1.2.13)
    JPEG:                        build-libjpeg-turbo (ver 2.1.3-62)
      SIMD Support Request:      YES
      SIMD Support:              NO
    WEBP:                        build (ver encoder: 0x020f)
    PNG:                         build (ver 1.6.37)
    TIFF:                        build (ver 42 - 4.2.0)
    JPEG 2000:                   build (ver 2.4.0)
    OpenEXR:                     build (ver 2.3.0)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      YES (prebuilt binaries)
      avcodec:                   YES (58.134.100)
      avformat:                  YES (58.76.100)
      avutil:                    YES (56.70.100)
      swscale:                   YES (5.9.100)
      avresample:                YES (4.0.0)
    GStreamer:                   NO
    DirectShow:                  YES
    Media Foundation:            YES
      DXVA:                      YES

  Parallel framework:            Concurrency

  Trace:                         YES (with Intel ITT)

  Other third-party libraries:
    Intel IPP:                   2020.0.0 Gold [2020.0.0]
           at:                   D:/a/opencv-python/opencv-python/_skbuild/win-amd64-3.7/cmake-build/3rdparty/ippicv/ippicv_win/icv
    Intel IPP IW:                sources (2020.0.0)
              at:                D:/a/opencv-python/opencv-python/_skbuild/win-amd64-3.7/cmake-build/3rdparty/ippicv/ippicv_win/iw
    Lapack:                      NO
    Eigen:                       NO
    Custom HAL:                  NO
    Protobuf:                    build (3.19.1)

  OpenCL:                        YES (NVD3D11)
    Include path:                D:/a/opencv-python/opencv-python/opencv/3rdparty/include/opencl/1.2
    Link libraries:              Dynamic load

  Python 3:
    Interpreter:                 C:/hostedtoolcache/windows/Python/3.7.9/x64/python.exe (ver 3.7.9)
    Libraries:                   C:/hostedtoolcache/windows/Python/3.7.9/x64/libs/python37.lib (ver 3.7.9)
    numpy:                       C:/hostedtoolcache/windows/Python/3.7.9/x64/lib/site-packages/numpy/core/include (ver 1.17.0)
    install path:                python/cv2/python-3

  Python (for build):            C:/ProgramData/chocolatey/bin/python2.7.exe

  Java:
    ant:                         NO
    JNI:                         C:/hostedtoolcache/windows/Java_Temurin-Hotspot_jdk/8.0.362-9/x64/include C:/hostedtoolcache/windows/Java_Temurin-Hotspot_jdk/8.0.362-9/x64/include/win32 C:/hostedtoolcache/windows/Java_Temurin-Hotspot_jdk/8.0.362-9/x64/include
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    D:/a/opencv-python/opencv-python/_skbuild/win-amd64-3.7/cmake-install
-----------------------------------------------------------------

已尝试的解决方法

  • 将脚本快捷方式权限提升至管理员级别
  • 多次重启应用
  • 检查以太网线缆(网络正常,VLC可正常播放该RTSP流)

解决方案

1. 强制指定FFMPEG后端

报错显示OpenCV误将RTSP URL识别为图片序列路径(触发CAP_IMAGES后端),原因是开机启动时OpenCV的后端优先级变化,未自动选择FFMPEG处理RTSP流。修改初始化代码,显式传入后端参数:

self.capture = cv2.VideoCapture(src, cv2.CAP_FFMPEG)

2. 延迟脚本启动

开机阶段网络可能未完全就绪,导致脚本执行时无法连接摄像头。在脚本开头添加延迟:

import time
time.sleep(10)  # 延迟时长可根据实际情况调整

3. 切换工作目录

开机启动时脚本的工作目录可能不是脚本所在目录,引发路径相关异常。在脚本开头切换到脚本所在目录:

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

4. 使用绝对路径调用Python解释器

修改开机启动快捷方式的目标,直接指向Python解释器并传入脚本绝对路径,示例:

"C:\Python310\python.exe" "D:\full\path\to\your\script.py"

内容的提问来源于stack exchange,提问作者Torch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:42:37