1 裁剪视频的原因

在有些情况下,我们只需要视频中间部分的视频内容,所以需要通过裁剪去掉周围冗余的视频部分。

2 代码

# -*- coding: utf-8 -*-

import cv2
import os

def crop_video_by_width(input_video_path,out_video_path):
    # 判断视频是否存在
    if not os.path.exists(input_video_path):
        print('输入的视频文件不存在')

    # 获取

    video_read_cap = cv2.VideoCapture(input_video_path)

    input_video_width = int(video_read_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    input_video_height = int(video_read_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    input_video_fps = int(video_read_cap.get(cv2.CAP_PROP_FPS))
    input_video_fourcc = int(cv2.VideoWriter_fourcc(*'XVID'))

    out_video_width = 512;
    out_video_height = 512;
    out_video_size = (int(out_video_width), int(out_video_height))

    video_write_cap = cv2.VideoWriter(out_video_path,input_video_fourcc,input_video_fps,out_video_size)

    while video_read_cap.isOpened():
        result, frame = video_read_cap.read()
        if not result:
            break

        # 裁剪到与原视频高度等宽的视频
        diff = input_video_width - input_video_height
        diff = int(diff/2)
        crop_start_index = int(diff)
        crop_end_index = int(diff + input_video_height)

        # 参数1 是高度的范围,参数2是宽度的范围
        target = frame[0:int(input_video_height),crop_start_index:crop_end_index]

        # 再resize到512x512
        target = cv2.resize(target,(out_video_width,out_video_height))

        video_write_cap.write(target)
        cv2.imshow('target',target)
        cv2.waitKey(10)

    video_read_cap.release()
    video_write_cap.release()

    cv2.destroyAllWindows()


if __name__ == '__main__':
    crop_video_by_width(r'cxk.mp4','result.mp4')

3 结果

未裁剪的视频截图:

Python – 使用python-opencv裁剪原视频为与视频高同宽的视频-StubbornHuang Blog

裁剪后的视频截图:
Python – 使用python-opencv裁剪原视频为与视频高同宽的视频-StubbornHuang Blog

如果您觉得对您有帮助,可以请站长喝一杯咖啡哦!

记得在赞赏备注里写上您的昵称

您可在本站资助名单中查看你的打赏记录哦!

支付宝扫一扫

微信扫一扫

金额随意,礼清义重

当前分类随机文章推荐

全站随机文章推荐

关于本站站长 StubbornHuang
Python – 使用python-opencv裁剪原视频为与视频高同宽的视频-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。