如何在opencv中显式访问mjpeg后端进行视频捕获

Posted

技术标签:

【中文标题】如何在opencv中显式访问mjpeg后端进行视频捕获【英文标题】:How to explicitly access mjpeg backend for videocapture in opencv 【发布时间】:2020-07-26 21:39:56 【问题描述】:

当我执行以下操作时:

availableBackends = [cv2.videoio_registry.getBackendName(b) for b in v2.videoio_registry.getBackends()]
print(availableBackends)

我收到['FFMPEG', 'GSTREAMER', 'INTEL_MFX', 'V4L2', 'CV_IMAGES', 'CV_MJPEG']

如果我现在尝试:

print(cv2.CAP_FFMPEG)
print(cv2.CAP_GSTREAMER)
print(cv2.CAP_INTEL_MFX)
print(cv2.CAP_V4L2)
print(cv2.CAP_IMAGES)
print(cv2.CAP_MJPEG)

除了最后一个AttributeError: module 'cv2.cv2' has no attribute 'CAP_MJPEG'之外的所有工作。

如何明确设置 cv2.CAP_MJPEG 后端(cv2.CAP_CV_MJPEG 也不起作用)?

【问题讨论】:

【参考方案1】:

你可以看到所有的标志here。

看起来cv2.CAP_OPENCV_MJPEG 就是您要查找的内容。


以下测试创建MJPEG合成AVI视频文件,并使用cv2.CAP_OPENCV_MJPEG后端读取视频:

import numpy as np
import cv2

#availableBackends = [cv2.videoio_registry.getBackendName(b) for b in cv2.videoio_registry.getBackends()]
#print(availableBackends)

print('cv2.CAP_OPENCV_MJPEG = ' + str(cv2.CAP_OPENCV_MJPEG))


intput_filename = 'vid.avi'

# Generate synthetic video files to be used as input:
###############################################################################
width, height, n_frames = 640, 480, 100  # 100 frames, resolution 640x480

# Use motion JPEG codec (for testing)
synthetic_out = cv2.VideoWriter(intput_filename, cv2.VideoWriter_fourcc(*'MJPG'), 25, (width, height))

for i in range(n_frames):
    img = np.full((height, width, 3), 60, np.uint8)
    cv2.putText(img, str(i+1), (width//2-100*len(str(i+1)), height//2+100), cv2.FONT_HERSHEY_DUPLEX, 10, (30, 255, 30), 20)  # Green number
    synthetic_out.write(img)

synthetic_out.release()
###############################################################################


# Read the video using CV_MJPEG backend
###############################################################################
cap = cv2.VideoCapture(intput_filename, cv2.CAP_OPENCV_MJPEG)

# Keep iterating break
while True:
    ret, frame = cap.read()  # Read frame from first video

    if ret:
        cv2.imshow('frame', frame)  # Display frame for testing
        cv2.waitKey(100) #Wait 100msec (for debugging)
    else:
        break

cap.release() #Release must be inside the outer loop
###############################################################################

【讨论】:

谢谢。这是我在网上搜索了好几个小时的正确解决方案。

以上是关于如何在opencv中显式访问mjpeg后端进行视频捕获的主要内容,如果未能解决你的问题,请参考以下文章

由于捕获缓冲区,OpenCV VideoCapture 滞后

OpenCV,无法为长记录释放 CAP_OPENCV_MJPEG VideoWriter

在 MIME 多部分消息中显式指定边界?

如何在 CoffeeScript 中显式返回对象

如何在 Django 中显式重置模板片段缓存?

如何在 lapply (R) 中显式定义附加参数