Python – 使用python-opencv裁剪原视频为与视频高同宽的视频
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Python – 使用python-opencv裁剪原视频为与视频高同宽的视频
原文链接:https://www.stubbornhuang.com/1464/
发布于:2021年07月28日 10:29:28
修改于:2021年07月28日 10:33:57

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 - 解决opencv-python使用cv2.imread()读取中文路径图片失败的问题 阅读43次,点赞0次
- 简单粗暴:使用pycharm安装对应的Python版本第三方包 阅读2889次,点赞0次
- Python - 判断一个字符串是否为json格式 阅读517次,点赞0次
- Python - 字典dict遍历方法总结 阅读35次,点赞0次
- Python - 不定长函数参数列表 阅读1396次,点赞0次
- Python - 普通函数/lambda匿名函数/类成员函数作为回调函数的用法 阅读1433次,点赞0次
- Python - 运算符/ or // or %的含义和区别 阅读1325次,点赞0次
- Python3 - 正则表达式去除字符串中的特殊符号 阅读11636次,点赞1次
- Pip - 常用命令(安装,卸载,升级第三方库) 阅读2570次,点赞1次
- Python - 使用Python+websockets时报错:AttributeError: module 'websockets' has no attribute 'serve' 阅读986次,点赞0次
全站随机文章推荐
- 资源分享 - Vulkan学习指南 , Learning Vulkan 中文版PDF下载 阅读390次,点赞0次
- 资源分享 - GPU Pro 360 - Guide to Lighting 英文高清PDF下载 阅读1733次,点赞0次
- 资源分享 - Game Programming Gems 3 英文高清PDF下载 阅读1381次,点赞0次
- 资源分享 - Jim Blinn's Corner - A Trip Down the Graphics Pipeline 英文高清PDF下载 阅读1756次,点赞2次
- 资源分享 - 深度学习框架Pytorch入门与实践(陈云著)PDF下载 阅读1967次,点赞0次
- Google Adsense - 使用招商银行电汇收款 阅读617次,点赞2次
- WordPress - 下载安装插件失败,无法创建目录 阅读3849次,点赞0次
- 资源分享 - PHP与MySQL程序设计(第3版) 中文 PDF下载 阅读1437次,点赞0次
- C++ - 使用Websocket++编写客户端连接WebSocket服务器并进行通信 阅读2514次,点赞2次
- 资源分享 - GPU Gems 1 - Programming Techniques, Tips and Tricks for Real-Time Graphics英文高清PDF下载 阅读2395次,点赞0次
评论
148