我的Python程序应该使用哪种OpenCV FOURCC编解码器?

2024-10-05 20:11:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经实现了一个Python脚本,它向用户显示视频并记录下来。视频被压缩或未压缩保存

在我看到的一个老程序中,使用了“DIVX”MPEG-4和“IYUV”编解码器。由于某些原因,它们不能在我的计算机上工作(输出的视频是MP4文件)

OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'

“MPJPG”编解码器与“.avi”文件一起工作

因为我不确定编解码器,我想问一下,我的脚本应该使用哪些编解码器来达到以下要求:

  • 视频序列可以保存为.mp3.mp4文件(均已压缩)或.avi文件(未压缩)
  • Python脚本应该在Windows和Linux平台上工作

这是我的源代码: main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import cv2
import platform

#=========== TO CHANGE ===========
INPUT_VIDEO = os.path.join("..", "resources", "video.mp4")
OUTPUT_VIDEO = os.path.join("..", "recorded", "recorded.avi")
compress = False
#=========== TO CHANGE ===========

WINDOW_NAME = "Video Recorder"

player = cv2.VideoCapture(INPUT_VIDEO)

# Get the frames per second (fps) of the video.
fps = player.get(cv2.CAP_PROP_FPS)

# Get width and height via the video capture property.
width = player.get(cv2.CAP_PROP_FRAME_WIDTH)
height = player.get(cv2.CAP_PROP_FRAME_HEIGHT)

# Define the codec and create VideoWriter object according to the used operating system.
four_cc = None
if platform.system() == "Windows":
    if compress:
        four_cc = cv2.VideoWriter_fourcc(*"MJPG")  # *"DIVX")  # DIVX MPEG-4 codec.
    else:
        four_cc = cv2.VideoWriter_fourcc(*"MJPG")  # *"IYUV")  # Uncompressed yuv420p in avi container.
elif platform.system() == "Linux":
    if compress:
        four_cc = cv2.VideoWriter_fourcc(*"DIVX")  # DIVX MPEG-4 codec.
    else:
        four_cc = cv2.VideoWriter_fourcc(*"IYUV")  # Uncompressed yuv420p in avi container.

recorder = cv2.VideoWriter(OUTPUT_VIDEO, four_cc, fps, (int(width), int(height)))

if player is None:
    quit()

while player.isOpened():
    ret, frame = player.read()

    if ret:
        cv2.imshow(WINDOW_NAME, frame)
        recorder.write(frame)
    else:
        break

    key_code = cv2.waitKey(1)

    # Closes the window if the ESC key was pressed.
    if key_code == 27:
        break

    # Closes the window if the X button of the window was clicked.
    if cv2.getWindowProperty(WINDOW_NAME, 1) == -1:
        break

player.release()
recorder.release()
cv2.destroyAllWindows()

我使用的是Windows7计算机,带有opencv contrib python 3.4.0.12和python 3.6


Tags: 文件the视频ifvideo编解码器cv2codec