Python OpenCV中的VideoCapture内存泄漏

Rem*_*miX 11 python webcam opencv memory-leaks v4l2

我正在使用3个网络摄像头偶尔在OpenCV中拍摄快照.它们连接到相同的usb总线,由于usb带宽限制,它不能同时允许所有3个连接(降低分辨率允许最多2个同时连接,而且我没有更多的usb总线).

因此,每次我想拍摄快照时都必须切换网络摄像头连接,但这会在大约40个开关后导致内存泄漏.

这是我得到的错误:

libv4l2: error allocating conversion buffer
mmap: Cannot allocate memory
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument

Unable to stop the stream.: Bad file descriptor
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
munmap: Invalid argument
libv4l1: error allocating v4l1 buffer: Cannot allocate memory
HIGHGUI ERROR: V4L: Mapping Memmory from video source error: Invalid argument
HIGHGUI ERROR: V4L: Initial Capture Error: Unable to load initial memory buffers.
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or 
unsupported array type) in cvGetMat, file 
/build/buildd/opencv-2.3.1/modules/core/src/array.cpp, line 2482

Traceback (most recent call last):
File "/home/irobot/project/test.py", line 7, in <module>
cv2.imshow('cam', img)
cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/array.cpp:2482: 
error: (-206) Unrecognized or unsupported array type in function cvGetMat
Run Code Online (Sandbox Code Playgroud)

这是一段生成此错误的简单代码:

import cv2

for i in range(0,100):
    print i
    cam = cv2.VideoCapture(0)
    success, img = cam.read()
    cv2.imshow('cam', img)
    del(cam)
    if cv2.waitKey(5) > -1:
        break

cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

也许值得注意的是,VIDIOC_QUERYMENU: Invalid argument每次相机连接时都会出现错误,但我仍然可以使用它.

作为一些额外的信息,这是我v4l2-ctl -V的网络摄像头输出:

~$ v4l2-ctl -V
Format Video Capture:
Width/Height  : 640/480
Pixel Format  : 'YUYV'
Field         : None
Bytes per Line: 1280
Size Image    : 614400
Colorspace    : SRGB
Run Code Online (Sandbox Code Playgroud)

是什么导致这些错误,我该如何解决?

bob*_*rti 1

错误消息的相关片段是 Unrecognized or unsupported array type in function cvGetMat。该cvGetMat()函数将数组转换为 Mat。Mat 是OpenCVC/C++ 领域中使用的矩阵数据类型(注意:OpenCV您正在使用的 Python 接口使用 Numpy 数组,然后在后台将其转换为 Mat 数组)。考虑到这一背景,问题似乎是您传递给的数组的格式cv2.imshow()不正确。两个想法:

  1. 这可能是由您的网络摄像头的奇怪行为引起的...在某些摄像头上,有时会返回空帧。在将 im 数组传递给 之前imshow(),请尝试确保它不为空。
  2. 如果每个帧都发生错误,请消除您正在执行的一些处理,并cv2.imshow()在从网络摄像头抓取帧后立即调用。如果仍然不起作用,那么您就会知道这是您的网络摄像头的问题。否则,逐行添加回处理,直到隔离问题。例如,从这个开始:

    while True:
    
    
    # Grab frame from webcam
    retVal, image = capture.read(); # note: ignore retVal
    
    #   faces = cascade.detectMultiScale(image, scaleFactor=1.2, minNeighbors=2, minSize=(100,100),flags=cv.CV_HAAR_DO_CANNY_PRUNING);
    
    # Draw rectangles on image, and then show it
    #   for (x,y,w,h) in faces:
    #       cv2.rectangle(image, (x,y), (x+w,y+h), 255)
    cv2.imshow("Video", image)
    
    i += 1;
    
    Run Code Online (Sandbox Code Playgroud)

来源:相关问题:OpenCV C++ Video Capture 似乎不起作用