本文整理了我在学习和工作中用到的实用python脚本,希望也能帮助到需要的小伙伴~
视频格式转换
- 安装视频处理库moviepy
pip install moviepy
- 安装FFmpeg(FFmpeg是一个开源的多媒体框架,moviepy库依赖于它来处理视频文件),下载参考流程:Mac版 下载安装FFmpeg
- 设置IMAGEIO_FFMPEG_EXE环境变量:如果您已经安装了FFmpeg,可以设置IMAGEIO_FFMPEG_EXE环境变量来指定FFmpeg可执行文件的路径。在命令行中执行以下命令:
对于Windows用户:set IMAGEIO_FFMPEG_EXE=path/to/ffmpeg.exe
对于Mac或Linux用户:export IMAGEIO_FFMPEG_EXE=/path/to/ffmpeg
请确保将"path/to/ffmpeg.exe"或"/path/to/ffmpeg"替换为您实际安装的FFmpeg可执行文件的路径。
- 编写代码(avi → mp4 为例)
from moviepy.editor import VideoFileClip
def convert_avi_to_mp4(input_file, output_file):
video = VideoFileClip(input_file)
video.write_videofile(output_file, codec='libx264')
input_file = 'input.avi'
output_file = 'output.mp4'
convert_avi_to_mp4(input_file, output_file)
- 运行以上脚本,即可将avi格式的视频转换为mp4格式的视频
pip快速下载命令
-i http://pypi.douban.com/simple --trusted-host pypi.douban.com
多进程处理百万图片数据集
from concurrent.futures import ProcessPoolExecutor
import os
import cv2
from tqdm import tqdm
from PIL import Image
data_path = "data.txt"
save_image_dir = '/data_root/'
save_path = 'data_save.txt'
os.makedirs(save_image_dir, exist_ok=True)
samples = open(data_path).readlines()
col1 = 480
col2 = 864
def process_sample(path):
path = path.strip()
img = Image.open(path)
img_crop = img.crop((0, col1, img.width, col2))
img_crop_resize = img_crop.resize((384, 384))
save_name = path.replace('/', '@')
image_path = save_image_dir + save_name
img_crop_resize.save(image_path)
return image_path
if __name__ == '__main__':
print('os.cpu_count()', os.cpu_count())
# 创建进程池,根据CPU核心数量决定进程数
with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:
results = list(tqdm(executor.map(process_sample, samples), total=len(samples)))
# 将结果写入文件
with open(save_path, "w") as outfile:
for image_path in results:
outfile.write(image_path + '\n')
print('Done!!')