Pillow怎么从大图像中快速裁剪出多个小图像

721
2024/5/6 11:06:11
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要从大图像中快速裁剪出多个小图像,你可以使用Pillow库的crop()函数来实现。以下是一个示例代码,演示如何使用Pillow库裁剪出多个小图像:

from PIL import Image

# 打开大图像
img = Image.open('large_image.jpg')

# 设置小图像的宽度和高度
small_img_width = 100
small_img_height = 100

# 设置裁剪起始点的横纵坐标
x = 0
y = 0

# 循环裁剪出多个小图像
for i in range(5):
    for j in range(5):
        cropped_img = img.crop((x, y, x + small_img_width, y + small_img_height))
        cropped_img.save(f'small_image_{i}_{j}.jpg')
        x += small_img_width

    x = 0
    y += small_img_height

在上面的代码中,我们首先打开了一个大图像,然后设置了小图像的宽度和高度。接下来,我们通过循环裁剪出多个小图像,并保存到磁盘上。你可以根据自己的需求调整小图像的宽度、高度和裁剪起始点的坐标来实现不同的裁剪效果。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Pillow怎么将文字转换为图像