python中视频音频的剪辑与处理实现案例代码

Python中轻松实现各种视频处理操作,包括剪辑、合并、添加音频、文本、特效等多种功能,主要介绍了python中视频音频的剪辑与处理实现,具有一定的参考价值,感兴趣的可以了解一下

视频:尺寸裁剪

import cv2


def extract_video_roi(src_video_path, dst_video_path, roi_start, roi_end):
    cap = cv2.VideoCapture(src_video_path)
    if not cap.isOpened():
        print(f"无法打开视频文件:{src_video_path}")
        return

    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)

    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    out = cv2.VideoWriter(dst_video_path, fourcc, fps, (roi_end[0] - roi_start[0], roi_end[1] - roi_start[1]))

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        roi_frame = frame[roi_start[1]:roi_end[1], roi_start[0]:roi_end[0]]
        out.write(roi_frame)

    cap.release()
    out.release()


# 示例用法
src_video_path = "test.mp4"
dst_video_path = "test3.mp4"
roi_start = (978, 178)
roi_end = (1684, 969)

extract_video_roi(src_video_path, dst_video_path, roi_start, roi_end)

图片:尺寸裁剪

def crop_images(folder_path, result_path, a, b, c, d):
    # 检查输入路径是否存在,如果不存在则创建
    if not os.path.exists(result_path):
        os.makedirs(result_path)

    # 遍历文件夹内的所有图片文件
    for filename in os.listdir(folder_path):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            # 打开图片文件
            image = Image.open(os.path.join(folder_path, filename))

            # 裁剪图片
            cropped_image = image.crop((a, b, c, d))

            # 保存裁剪后的图片
            cropped_image.save(os.path.join(result_path, filename))

            # 关闭图片文件
            image.close()


folder_path = "标定1"
result_path = "标定2"
a, b, c, d = 84, 193, 1638, 934
crop_images(folder_path,result_path, a, b, c, d)

视频:每秒提取一张图片

import cv2
import os


def extract_frames(video_path, result_folder):
    # 创建结果文件夹
    os.makedirs(result_folder, exist_ok=True)

    # 打开视频文件
    cap = cv2.VideoCapture(video_path)

    frame_count = 0
    saved_count = 0
    # fps = cap.get(cv2.CAP_PROP_FPS)  # 获取视频的帧率
    frame_interval = int(cap.get(cv2.CAP_PROP_FPS))  # 设置帧采样间隔为1秒
    while cap.isOpened():
        # 读取视频帧
        ret, frame = cap.read()

        if not ret:
            break

        frame_count += 1
        # 每秒保存一帧
        if frame_count % frame_interval == 0:
            saved_count += 1

            # 保存帧到结果文件夹
            # frame_path = os.path.join(result_folder, f"{saved_count}.jpg")
            frame_path = os.path.join(result_folder, '%s.jpg' % saved_count)
            print(frame_path)
            cv2.imwrite(frame_path, frame)

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


# 文件夹路径不能有中文!!!!!!
video_path, result_folder = 'test3.mp4', 'new_folder'
extract_frames(video_path, result_folder)

视频音频:倍速,合并,裁剪

注意,下面的start和end单位是秒数,比如你想截取视频第一分钟的片段,那么start=0,end=60。

from moviepy.editor import *


def video_clip(file_name, save_name, start, end):
    """视频剪辑"""
    clip = VideoFileClip(file_name).subclip(start, end)
    clip.write_videofile(save_name)


def audio_clip(file_name, save_name, start, end):
    """音频剪辑"""
    audio = AudioFileClip(file_name).subclip(start, end)
    audio.write_audiofile(save_name)


def video2audio(file_name, save_name):
    """视频转音频"""
    # video = CompositeVideoClip([VideoFileClip(file_name).subclip(50, 60)])
    # video.write_videofile(save_name)
    my_audio_clip = AudioFileClip(file_name)
    my_audio_clip.write_audiofile(save_name)


def video_contact(files, save_name):
    """视频合并"""
    files = [VideoFileClip(i) for i in files]
    final_clip = concatenate_videoclips(files)
    final_clip.write_videofile(save_name)


def audio_contact(files, save_name):
    """音频合并"""
    files = [AudioFileClip(i) for i in files]
    final_clip = concatenate_audioclips(files)
    final_clip.write_audiofile(save_name)


def change_speed(file, save_name, speed):
    """改变速度"""
    clip = VideoFileClip(file)
    video_1 = clip.speedx(speed)
    video_1.write_videofile(save_name)


def get_gif(file, save_name, start, end):
    """视频转gif"""
    clip = VideoFileClip(file).subclip(start, end)
    clip.write_gif(save_name, fps=5)  # 生成之后的文件小,fps决定了文件大小


if __name__ == "__main__":
    pass

图片:转为视频

import cv2
import os
from PIL import Image

def PicToVideo(imgPath, videoPath, fps):
    images = os.listdir(imgPath)  # 获取所有图片名称
    images.sort(key=lambda x: int(x[:-4]))  # 对图片进行排序
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 设置视频的编码格式
    im = Image.open(imgPath + images[0])  # 获取图片信息
    videoWriter = cv2.VideoWriter(videoPath, fourcc, fps, im.size, isColor=True)  # 创建一个videoWriter对象,用于将图片保存为视频的一部分
    for im_name in images:
        print("已经载入图片" + im_name)
        frame = cv2.imread(imgPath + im_name)
        videoWriter.write(frame)
    videoWriter.release()  # 释放
    print("视频制作完毕")


if __name__ == "__main__":
    # imgPath:图片的保存文件夹
    # videoPath:视频路径
    # fps:帧率
    # 注意:图片大小要一致
    imgPath = "data/"
    videoPath = "result.mp4"
    fps = 1
    PicToVideo(imgPath, videoPath, fps)

图片:批量转灰度图

import cv2
import os


def to_gray(input_path, output_path):
    images = os.listdir(input_path)
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    for image in images:
        print(image)
        input_image = os.path.join(input_path, image)
        output_image = os.path.join(output_path, image)
        image = cv2.imread(input_image, cv2.IMREAD_GRAYSCALE)
        cv2.imwrite(output_image, image)


if __name__ == '__main__':
    input_path = "right"  # 要处理的图片所在的文件夹
    output_path = "right2"  # 处理完的图片放在这里
    to_gray(input_path, output_path)

图片:改变图片尺寸

if __name__ == "__main__":
    path = "no.png"
    save = "no2.png"
    pic = Image.open(path)
    pic.thumbnail((50, 50))
    pic.save(save, "png")

到此这篇关于python中视频音频的剪辑与处理实现的文章就介绍到这了,更多相关python 视频音频剪辑处理内容请搜索QQ沐编程以前的文章或继续浏览下面的相关文章希望大家以后多多支持QQ沐编程

© 版权声明
THE END
喜欢就支持一下吧
点赞5赞赏 分享