python 处理视频的简单 例子

moviepy

# 项目文档:https://zulko.github.io/moviepy/getting_started/quick_presentation.html
# Import everything needed to edit video clips
from moviepy.editor import *
from pathlib import Path
current_path = Path().absolute() 	

# Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60
clip = VideoFileClip(os.path.join(current_path, "video.mp4")).subclip(50,60)

# Reduce the audio volume (volume x 0.8)
clip = clip.volumex(0.8)

# Generate a text clip. You can customize the font, color, etc.
txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')

# Say that you want it to appear 10s at the center of the screen
txt_clip = txt_clip.set_pos('center').set_duration(10)

# Overlay the text clip on the first video clip
video = CompositeVideoClip([clip, txt_clip])

# Write the result to a file (many options available !)
video.write_videofile("myHolidays_edited.webm")

opencv

# 安装 pip install opencv-python
import cv2
import os
current_path = os.path.dirname(os.path.abspath(__file__))

file_path = os.path.join(current_path, "video.mp4")
# 打开视频文件
cap = cv2.VideoCapture(file_path)

# 获取视频帧率
fps = int(cap.get(cv2.CAP_PROP_FPS))

# 设置关键帧间隔
keyframe_interval = 5  # 每隔 5 秒导出一张关键帧

# 初始化帧计数器和时间计数器
frame_count = 0
time_count = 0

# 循环读取视频帧
while True:
    # 读取一帧
    ret, frame = cap.read()

    # 如果读取失败,则退出循环
    if not ret:
        break

    # 增加帧计数器和时间计数器
    frame_count += 1
    time_count += 1

    # 如果时间计数器超过关键帧间隔,则导出当前帧为关键帧
    if time_count >= keyframe_interval * fps:
        # 重置时间计数器
        time_count = 0

        # 生成关键帧文件名
        filename = f'frame{frame_count:04d}.jpg'

        # 保存关键帧为图片文件
        try:
            file_path = os.path.join(current_path, filename)
            #imwrite 写入 file_path不能包含中文,因为imwrite()函数使用的是C++库,在处理路径时使用的是系统默认的编码方式
            # success = cv2.imwrite(path, frame)
            # 新方法
            cv2.imencode('.jpg', frame)[1].tofile(file_path)
            print(f'Save {filename}')
        except Exception as e:
            print(e)

# 释放视频文件
cap.release() 

作者:spike

分类: Python

创作时间:2024-09-27

更新时间:2024-12-09