先安装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. 使用Camtasia 让照片变身动态视频

    视觉化影像已经慢慢渗入我们平日的生活了,很多人已经慢慢地从单纯的文字记录,发展到使用照片记录生活,而视频化的记录也随着智能手机的普及而迅速发展起来.对于一些曾经使用照片记录的瞬间,我们也可以将其变身为 ...

  2. 头秃了,使用@AutoConfigureBefore指定配置类顺序竟没生效?

    持续原创输出,点击上方蓝字关注我 前言 日常工作中对于Spring Boot 提供的一些启动器可能已经足够使用了,但是不可避免的需要自定义启动器,比如整合一个陌生的组件,也想要达到开箱即用的效果. 在 ...

  3. Python GUI之Tkiner实战

    前言 Tkinter 是 Python 的标准 GUI 库.Python 使用 Tkinter 可以快速的创建 GUI 应用程序. 由于 Tkinter 是内置到 python 的安装包中.只要安装好 ...

  4. pytest参数化

    Pytest可以在多个级别上实现测试参数化 一.@pytest.fixture装饰器调用参数 示例 import pytest from selenium import webdriver from ...

  5. Linux root目录空间过小,加大空间

    1. 查看还有多少空间可以使用: df -h 这里可以看出来home的空间还很大,可以分配给root 2. 扩容根目录的思路如下: 将/home文件夹备份,删除/home文件系统所在的逻辑卷,增大/文 ...

  6. C语言讲义——指针函数和函数指针

    指针函数 返回值是指针的函数,如void* malloc(...) #include<stdio.h> #include<stdlib.h> #include<strin ...

  7. Java基础教程——Math类

    Math Java这种级别的编程语言怎么可能没有数学相关的操作呢? java.lang.Math类提供了基本数学运算的方法. 该类是final的,说明不能被继承. 该类的构造方法是私有的(privat ...

  8. 【原创】视频+文字:详解VBA解决数独问题

    [说在前面]: 之前,我在微信朋友圈看到一个同事发了一个状态,说的是她在家辅导孩子做作业,一个数独的题目,好像没有做出来.我看了下,我也做不出来,后来仔细想了下,花了两个多小时时间,用Python编了 ...

  9. Python爬虫入门(二)之Requests库

    Python爬虫入门(二)之Requests库 我是照着小白教程做的,所以该篇是更小白教程hhhhhhhh 一.Requests库的简介 Requests 唯一的一个非转基因的 Python HTTP ...

  10. CentOS 7下安装Docker

    安装一些必要的系统工具: sudo yum install -y yum-utils device-mapper-persistent-data lvm2 添加软件源信息: sudo yum-conf ...