先安装ffmpeg

pip install ffmpeg-python -i https://pypi.tuna.tsinghua.edu.cn/simple

下面是代码,新建video_compress.py

import sys
import os
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor # 线程池,进程池
# import zlib
import threading
# import platform
# from PIL import Image
import ffmpeg
from shutil import copyfile def get_file_dir(file):
"""获取文件目录通用函数"""
fullpath = os.path.abspath(os.path.realpath(file))
return os.path.dirname(fullpath) def SaveVideo(input_file):
file_name = os.path.basename(input_file)
arr = file_name.split('.')
new_file_name = arr[0] + '_compress.' + arr[1]
output_path = os.path.join(get_file_dir(input_file), 'compress_output')
output_file = os.path.join(output_path, new_file_name)
if not os.path.isdir(output_path):
os.makedirs(output_path)
if (os.path.exists(output_file)):
print("已存在,跳过压缩")
return
# 执行probe执行
probe = ffmpeg.probe(input_file)
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
if video_stream is None:
print('No video stream found', file=sys.stderr)
return
# sys.exit(1)
# 宽度
width = int(video_stream['width'])
# # 高度
height = int(video_stream['height'])
# # 帧数
# num_frames = int(video_stream['nb_frames'])
# # 时长
# time = (video_stream['duration'])
# 比特率
bitrate = (video_stream['bit_rate']) # print('width: {}'.format(width))
# print('height: {}'.format(height))
# print('num_frames: {}'.format(num_frames))
# print('time: {}'.format(time))
# print('bitrate: {}'.format(bitrate))
if ((width == 720 and height == 1280) or (width == 1280 and height == 720)):
if (int(bitrate) < 2500 * 1024):
print("比特率过小,跳过压缩")
try:
copyfile(input_file, output_file)
except IOError as e:
print("Unable to copy file. %s" % e)
return
elif ((width == 1080 and height == 1920) or (width == 1920 and height == 1080)):
if (int(bitrate) < 5000 * 1024):
print("比特率过小,跳过压缩")
try:
copyfile(input_file, output_file)
except IOError as e:
print("Unable to copy file. %s" % e)
return
else:
if (int(bitrate) < 2000 * 1024):
print("比特率过小,跳过压缩")
try:
copyfile(input_file, output_file)
except IOError as e:
print("Unable to copy file. %s" % e)
return fpsize = os.path.getsize(input_file) / 1024
if fpsize >= 150.0: # 大于150KB的视频需要压缩
compress = "ffmpeg -i {} -r 25 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -crf 26 -profile:v baseline -acodec aac -b:a 96k -strict -2 {}".format(input_file, output_file)
isRun = os.system(compress)
# if outName:
# compress = "ffmpeg -i {} -r 25 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -crf 24 -profile:v baseline -acodec aac -b:a 128k -strict -2 {}".format(
# fileInputPath, fileOutPath)
# isRun = os.system(compress)
# else:
# compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileInputPath)
# isRun = os.system(compress)
if isRun != 0:
return (isRun, "没有安装ffmpeg")
return True
else:
return True def Compress_Video(self):
# 异步保存打开下面的代码,注释同步保存的代码
thr = threading.Thread(target=self.SaveVideo)
thr.start() def check_path(input_path):
"""如果输入的是文件则直接压缩,如果是文件夹则先遍历"""
if os.path.isfile(input_path):
SaveVideo(input_path)
elif os.path.isdir(input_path):
dirlist = os.walk(input_path)
for root, dirs, files in dirlist:
if (not (root.endswith("\\compress_output") or root.endswith("/compress_output"))):
i = 0
for filename in files:
i = i + 1
SaveVideo(os.path.join(root, filename))
# process_pool.submit(SaveVideo, os.path.join(root, filename))
# compress_by_tinypng(os.path.join(root, filename))
else:
print(u'目标文件(夹)不存在,请确认后重试。') if __name__ == "__main__":
process_pool = ProcessPoolExecutor(1) # 定义5个进程
b = sys.argv[1:] # 测试压缩
len_param = len(sys.argv)
if len_param != 2:
print('请使用: %s [inputpath] [outputpath]' %
os.path.basename(sys.argv[0]))
else:
check_path(b[0])
input("Press <enter> 请耐心等待\n")


-crf 控制视频输出质量,取值范围为0-51,0为无损,从主观上讲,18-28是一个合理的范围

最后执行命令 python video_compress.py /Users/xx/test

如果要还原压缩后视频详细信息请参考 https://www.cnblogs.com/xiaocaidev/p/13617120.html

python 批量压缩手机视频的更多相关文章

  1. tinypng的python批量压缩图片功能

    tinypng网站提供的图片压缩功能很不错,但是直接在网站上压缩有限制,大量压缩图片时比较麻烦,还好官方提供了很多脚本的自动化压缩接口.下面简单说下python批量压缩步骤. 1.申请api key ...

  2. Python 批量下载BiliBili视频 打包成软件

    文章目录 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人,我给大家 ...

  3. 10 行 Python 代码,批量压缩图片 500 张,简直太强大了

    本文原创并首发于公众号[Python猫],未经授权,请勿转载. 原文地址:https://mp.weixin.qq.com/s/5hpFDgjCpfb0O1Jg-ycACw 熟悉 "Pyth ...

  4. python批量处理压缩文件

    python批量处理压缩文件 博客小序:在数据的处理中,下载的数据很有可能是许多个压缩文件,自己一个一个解压较为麻烦,最近几日自己在处理一次下载的数据时,遇到大量的压缩数据需要处理,于是利用pytho ...

  5. 使用Python轻松批量压缩图片

    在互联网,图片的大小对一个网站的响应速度有着明显的影响,因此在提供用户预览的时候,图片往往是使用压缩后的.如果一个网站图片较多,一张张压缩显然很浪费时间.那么接下来,我就跟大家分享一个批量压缩图片的方 ...

  6. python 无损压缩照片,支持批量压缩,支持保留照片信息

    由于云盘空间有限,照片尺寸也是很大,所以写个Python程序压缩一下照片,腾出一些云盘空间 1.批量压缩照片 新建 photo_compress.py 代码如下 1 # -*- coding: utf ...

  7. ios怎样实现快速将显卡中数据读出压缩成视频在cocos2dx扩展开发中

    如果解决ios怎样实现快速将显卡中数据读出压缩成视频在cocos2dx扩展开发中 手机平台性能是个关键问题. 压缩视频分成3个步骤: 读取显卡数据, 使用编码器压缩,保存文件. 使用libav 压缩的 ...

  8. 基于Socket的Android手机视频实时传输

    首先,简单介绍一下原理.主要是在手机客户端 (Android)通过实现Camera.PreviewCallback接口,在其onPreviewFrame重载函数里面获取摄像头当前图像数据, 然后通过S ...

  9. 运营商手机视频流量包业务日志ETL及统计分析

    自己做过的项目在这里做一个记录,否则就感觉不是自己的了.一是因为过去时间已经很长了,二是因为当时做得有点粗糙,最后还不了了之了. 话不多说,先大致介绍一下项目背景.以前各大手机视频 App 一般都有运 ...

随机推荐

  1. Guitar Pro吉他指弹入门——美式指弹

    说起指弹吉他,很多身边的琴友首先反应到的是押尾桑,岸部真明,伍伍慧等等指弹艺术家的日式指弹.笔者在初涉指弹的时候,也是如此,但是随着学习的加深,首先认识到了汤米大神(Tommy Emmanuel),然 ...

  2. 如何使用OCR编辑器检查和识别文本

    ABBYY FineReader 15(Windows系统)中的OCR编辑器能帮助用户对扫描仪或者数码相机获取的图像文件进行自动文本识别,OCR区域绘制等,使这些图像文件能进一步转换为可编辑的格式.其 ...

  3. [工具推荐]制作基于Dash的本地文档方便搜索文档api和内容

    [版权声明]:本文章由danvid发布于http://danvid.cnblogs.com/,如需转载或部分使用请注明出处 最近在看es的文档,发现查起api来真的很麻烦,很多现在开源的文档都没有查询 ...

  4. vulnhub: DC 2

    首先地址探测找到主机IP: root@kali:~# nmap -sn 192.168.74.139/24 Starting Nmap 7.80 ( https://nmap.org ) at 202 ...

  5. 一:robot framework环境安装

    1.安装robot framework: 打开cmd进入dos下,输入 pip install robotframework Microsoft Windows [版本 10.0.18362.267] ...

  6. dubbo起停之服务注解

    开始之前建议先去了解spring的BeanDefinition可以参考下这里:https://www.jianshu.com/p/56e42e82e9a0 当用户使用注解@DubboComponent ...

  7. sqli-labs-master less05 前 知识点学习

    1. left()函数: left(a,b)从左侧截取a的前b位,正确则返回1,错误则返回0 例: select left(database(),1)='s'   结果返回1 先查询数据库 datab ...

  8. 自学linux——18.FTP服务器的搭建

    Centos7下FTP服务器的搭建 一.FTP的作用 文件传输协议(File Transfer Protocol,FTP),是一种在互联网中进行文件传输的协议,基于客户端/服务器模式,默认使用 20. ...

  9. IEEE754标准浮点数表示与舍入

    原文地址:https://blog.fanscore.cn/p/26/ 友情提示:本文排版不太好,但内容简单,请耐心观看,总会搞懂的. 1. 定点数 对于一个无符号二进制小数,例如101.111,如果 ...

  10. SpringBoot系列:六、集成Swagger文档

    本篇开始介绍Api文档Swagger的集成 一.引入maven依赖 <dependency> <groupId>io.springfox</groupId> < ...