python video file format and resolution conversion

Only one opencv is enough, opencv is really strong.
Precautions:

  1. source_path and sink_path need to be modified;
  2. This version supports the conversion of mov suffix to avi suffix, and the source code needs to be modified according to the actual situation;
# 目标
# 1. 拷贝视频文件并修改后缀
# 2. 修改图片的分辨率
# 3. 批量完成

import os
import cv2
from pathlib import Path


source_path = r".\mov_video"
sink_path = r".\data\videos"

if not os.path.exists(source_path) or not os.path.exists(sink_path):
    print('Path not exit!')
    exit()

videos_list = os.listdir(source_path)

for video in videos_list:
    video_path = os.path.join(source_path, video)
    if Path(video_path).suffix in ['.MOV', '.mov']:
        # 修改后缀名
        dis_video_name = video
        dis_video_name = dis_video_name.replace(str(dis_video_name).split('.')[-1], 'avi')
        dis_path = os.path.join(sink_path, dis_video_name)

        # 进行转换
        cap = cv2.VideoCapture(video_path)
        success, _ = cap.read()
        # 重新合成的视频在原文件夹,如果需要分开,可以修改file_n
        video_writer = cv2.VideoWriter(dis_path, cv2.VideoWriter_fourcc(*'XVID'), 25, (1280, 720))
        while success:
            success, vid1 = cap.read()
            try:
                vid = cv2.resize(vid1, (1280, 720), interpolation=cv2.INTER_LINEAR)  # 希望的分辨率大小可以在这里改
                video_writer.write(vid)
            except:
                break
                

Others can be ignored, but you have to read the reference link:
OpenCV uses VideoWriter to create video (Python version) : This article is really well written, a class and parameters are explained very clearly.
python+opencv batch modification of video resolution : This article will talk about it The actual application is
to copy the video through python : copy the video file like reading the file

Guess you like

Origin blog.csdn.net/weixin_42442319/article/details/125716706