前言

突发奇想,记录一下

使用

在使用之前确保安装了 Pillow

1
pip install Pillow

在这个示例中,我们将使用 Python 编写一个脚本,用于批量切割文件夹中的图片。每个图片都将被分割成 15 个小图片,按照从左到右、从上到下的顺序排列。切割出的小图片将被保存到单独的文件夹中,并且原图也会被保留。

步骤

1. 导入所需库

我们将使用os模块来处理文件和文件夹操作,以及PIL库(Python Imaging Library)来处理图片。

1
2
import os
from PIL import Image

2. 定义图片切割函数

我们需要定义一个函数,用于将单个图片切割成小图片并保存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def split_image(image_path, output_dir):
image = Image.open(image_path)
width, height = image.size
tile_size = 420 // 3 # 每个小图片的边长

count = 1 # 计数器,用于给分割出的小图片进行重命名
for y in range(0, height, tile_size):
for x in range(0, width, tile_size):
box = (x, y, x + tile_size, y + tile_size)
tile = image.crop(box)

# 创建输出文件夹
os.makedirs(output_dir, exist_ok=True)

# 保存分割出的小图片
tile_path = os.path.join(output_dir, f"{count}.{image.format.lower()}")
tile.save(tile_path)

count += 1

# 保存原图
original_path = os.path.join(output_dir, f"original.{image.format.lower()}")
image.save(original_path)

3. 编写主函数

我们需要编写一个主函数来遍历输入文件夹中的每个图片,并调用切割函数进行处理。

1
2
3
4
5
6
7
8
9
10
11
def main():
input_dir = "path/to/input/folder" # 输入文件夹路径
output_base_dir = "path/to/output/folder" # 输出文件夹的基础路径

# 遍历输入文件夹中的图片
for i, filename in enumerate(os.listdir(input_dir)):
if filename.endswith((".jpg", ".jpeg", ".png")):
image_path = os.path.join(input_dir, filename)
output_dir = os.path.join(output_base_dir, f"pic{i+1}")

split_image(image_path, output_dir)

4. 执行主函数

在脚本的末尾,我们需要添加以下代码来执行主函数。

1
2
if __name__ == "__main__":
main()

使用说明

在使用这个脚本时,需要将"path/to/input/folder"替换为包含要切割图片的文件夹的实际路径,将"path/to/output/folder"替换为你想要保存输出文件夹的实际路径。

脚本将遍历输入文件夹中的每个图片,将每个图片切割为 15 个小图片,并将它们保存在以pic1pic2等命名的文件夹中。同时,原图也会被保存在相应的输出文件夹中,并以original.jpgoriginal.png等命名。

请确保你的环境中已安装所需的库,可以通过运行pip install pillow来安装 Pillow 库。

以上就是批量切割文件夹中图片的 Python 脚本的编写过程。

记得将"path/to/input/folder""path/to/output/folder"替换为实际的文件夹路径。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
from PIL import Image

def split_image(image_path, output_dir):
image = Image.open(image_path)
width, height = image.size
tile_size = 420 // 4 # 每个小图片的边长

count = 1 # 计数器,用于给分割出的小图片进行重命名
for y in range(0, height, tile_size):
for x in range(0, width, tile_size):
box = (x, y, x + tile_size, y + tile_size)
tile = image.crop(box)

# 创建输出文件夹
os.makedirs(output_dir, exist_ok=True)

# 保存分割出的小图片
tile_path = os.path.join(output_dir, f"{count}.{image.format.lower()}")
tile.save(tile_path)

count += 1

# 保存原图
original_path = os.path.join(output_dir, f"all.{image.format.lower()}")
image.save(original_path)

# 主函数
def main():
input_dir = "input_folder" # 输入文件夹路径
output_base_dir = "output_folder" # 输出文件夹的基础路径

# 遍历输入文件夹中的图片
for i, filename in enumerate(os.listdir(input_dir)):
if filename.endswith((".jpg", ".jpeg", ".png")):
image_path = os.path.join(input_dir, filename)
output_dir = os.path.join(output_base_dir, f"pic{i+1}")

split_image(image_path, output_dir)

if __name__ == "__main__":
main()