效果图:

代码:

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
import os

from PIL import Image

def cut_image(image):
width, height = image.size
item_width = int(width / 3)
box_list = []
# (left, upper, right, lower)
for i in range(0,3):
for j in range(0,3):
# print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
box_list.append(box)
image_list = [image.crop(box) for box in box_list]
return image_list


def save_images(image_list, savepath, name):
index = 1
for image in image_list:
image.save(f"{savepath}/{name}_{str(index)}.bmp", 'BMP')
index += 1

if __name__ == '__main__':
print("开始处理图片...\n")
leadpath = './image' # 大文件路径
savepath = './newimg' # 下图文件路径
if not os.path.exists(savepath):
os.makedirs(savepath)

imgs = os.listdir(leadpath)
for img in imgs:

file_path = f"{leadpath}/{img}"
print(f"正在处理:{file_path}\r")
image = Image.open(file_path)
image_list = cut_image(image)
names = os.path.splitext(img)
save_images(image_list, savepath, names[0])
print("\r")
input("操作完成,按任意键退出...")