Use ffmpeg to scale pictures in batches based on Python

Use ffmpeg to scale pictures in batches based on Python

I. Introduction

​ Due to project reasons or personal writing needs, the author often has to write a large number of technical documents. The documents usually need to be accompanied by pictures, but there is a rather annoying problem with the pictures: the screenshots are of different sizes, and the width usually needs to be adjusted manually, which is very troublesome. Is there a good way to solve it? Yes, we can use batch image processing software to adjust the width of the images to be the same in advance, and the length is scaled according to the ratio, so that when inserting images in a document, there is no need to adjust them one by one, and most of them can be used directly.

​ There are many such software on the market, Baidu and Zhihu have a lot of them, they have exquisite interface, simple operation, and powerful toolbox, free advertising and paid themes... Anyway, they are not loved by the author.

​ Based on the above reasons, the author's attention has shifted to open source software. I have done video processing with ffmpeg before, and its powerful functions have left a deep impression on the author. With the software, to achieve batch processing, you need to write scripts to automatically traverse the folders and extract them, and then call ffmpeg for processing. There are many options: matlab script, BAT script, Python script. Matlab is powerful but also extremely large, give up. BAT script is easy to use but difficult to write, give up. Finally, this article writes a script based on Python script to call ffmpeg to achieve batch scaling of pictures.

​ The code in this article refers to the blogger: Xingshen Earthquake 's article. The original text deals with video files, which are used for format conversion. The author rewrites the code to realize the zooming of pictures. Interested readers can move to the original article:

Original link : https://blog.csdn.net/qq446252221/article/details/111679491

2. Introduction to ffmpeg

​ ffmpeg is a powerful open source audio and video processing software, which is called by netizens as a "Multimedia Processing Artifact" . It was written and open sourced by the famous genius programmer Fabrice Bella . You may not have heard of ffmpeg, but most readers must have used ffmpeg as the core video player and audio and video tool: Mplayer, ffplay, Shooter Player, Baofeng Video, KMPlayer, QQ Video, Format Factory, etc., and many more The player uses the open source ffmpeg but does not publish it.

​ It is usually used to process audio and video data, and it is used to process pictures in this article, which can be described as overkill.

​ For readers who are interested in batch scripts, software installation must not be a problem. The author does not waste time here, just search and install it by himself. After installation, remember to change the ffmpeg path to your own installation path in the author's script code.

​ Finally, Fabrice Bella is simply a god. If you are interested, you can look for his resume.

insert image description here

3. Python

​ This, I don’t want to say more, just say one sentence**: "Life is short, I use Python"**, readers, install it yourself.

​ The steps to use this script are:

  1. Install Python (installed can be ignored)

  2. Install ffmpeg (installed can be ignored)

  3. Copy the script to the root directory where the picture is located, and modify the following macro definitions in the script code: ffmpeg path, length and width parameters, and picture extension to be processed.

  4. Call the script with the following command in this directory:

    python '.\Picture Process.py'
    

    ​ After the script finishes running, a **"NewPicture"** folder will be created in the upper directory of the source file directory, and the zoomed pictures will be stored in it.

Fourth, the script running effect

  1. Source picture resolution 1718*636

    insert image description here

  2. The processed image resolution is 800*296

    insert image description here

    All newly generated images are scaled according to the script parameters with a width of 800 and a height proportional to the scale. That is: pictures smaller than this resolution will be enlarged, and pictures larger than this resolution will be reduced.

5. Source code

​ Finally, paste the source code:

import os
from turtle import heading
 
#设置ffmpeg路径
EXE_PATH="D:\\ffmpeg\\bin\\ffmpeg.exe"
#源图像路径
src_dir = ".\\"
#目标路径
dst_dir = "..\\NewPicture\\"
#图片文件扩展名
src_name= ".jpg"

# ffmpeg参数设置
#设置长度
width = 800
#设置宽度
height = -1
# 二者任何一个参数为-1时,将保持比例跟随另一个参数缩放 

""" Picture_Zoom函数定义
调用ffmpeg """
def Picture_Zoom(exe_path, src_path, dst_path):
	# 命令编辑
	cmd_line = '%s -i "%s" -vf scale="%s":"%s" -q 1 "%s"' % (exe_path, src_path,width,height,dst_path)
	# 调用命令行
	ret = os.system(cmd_line)
	if ret == 0:
		return True
	else:
		return False

""" Process_dir函数定义
遍历目录下所有文件并调用ffmpeg处理 """
def Process_dir(exe_path, src_dir, dst_dir):
	# 判断源目录是否存在
	if not os.path.exists(src_dir):
		print("The directory does not exist!")
		return
	#判断目标目录是否存在,若目标路径已存在,
	#先删除原来的旧目录
	if os.path.exists(dst_dir):
		# 调用CMD命令“rmdir”删除旧目录
		os.system('rmdir /s/q "%s"' % dst_dir)
	# 新建目标目录
	if not os.path.exists(dst_dir):
		os.mkdir(dst_dir)
	# 枚举源目录下的文件
	picture_list = os.listdir(src_dir)
	# 遍历指定扩展名的图像文件并处理
	for file in picture_list:
		if file.endswith(src_name):
			print("+Convert file:", file)
			# 生成新的源图片路径
			src_path = src_dir + file
			# 生成新的目标图片路径
			dst_path = dst_dir + file
			# 调用ffmpeg进行缩放
			Picture_Zoom(exe_path, src_path, dst_path)
 
Process_dir(EXE_PATH,src_dir, dst_dir)

#By ZhangJianCe 2022.3.17

Guess you like

Origin blog.csdn.net/lone5moon/article/details/123547179