How to explicitly access mjpeg backend for videocapture in opencv

北慕城南 提交于 2021-02-08 05:10:55

问题


When I execute following:

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

I get ['FFMPEG', 'GSTREAMER', 'INTEL_MFX', 'V4L2', 'CV_IMAGES', 'CV_MJPEG'].

If I now try:

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)

all work except the last one AttributeError: module 'cv2.cv2' has no attribute 'CAP_MJPEG'.

How can I explicitely set cv2.CAP_MJPEG backend (cv2.CAP_CV_MJPEG does also not work)?


回答1:


You can see all the flags here.

It looks like cv2.CAP_OPENCV_MJPEG is what you are looking for.


The following test creates MJPEG synthetic AVI video file, and reads the video using cv2.CAP_OPENCV_MJPEG backend:

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
###############################################################################


来源:https://stackoverflow.com/questions/61202978/how-to-explicitly-access-mjpeg-backend-for-videocapture-in-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!