gpt4 book ai didi

python - 使用 Python Image Library 将一张图片切割成多张图片

转载 作者:太空狗 更新时间:2023-10-29 17:21:14 29 4
gpt4 key购买 nike

我需要使用 PIL 将这张图片分成三部分,然后选择中间部分。我该怎么做?

http://thedilbertstore.com/images/periodic_content/dilbert/dt110507dhct.jpg

最佳答案

假设您有一张像这样的很长的图片。

Picture

现在你想把它切成更小的垂直位,因为它太长了。

这是一个 Python 脚本,可以执行此操作。这对我为 LaTeX 文档准备非常长的图像很有用。

from __future__ import division
import Image
import math
import os

def long_slice(image_path, out_name, outdir, slice_size):
"""slice an image into parts slice_size tall"""
img = Image.open(image_path)
width, height = img.size
upper = 0
left = 0
slices = int(math.ceil(height/slice_size))

count = 1
for slice in range(slices):
#if we are at the end, set the lower bound to be the bottom of the image
if count == slices:
lower = height
else:
lower = int(count * slice_size)
#set the bounding box! The important bit
bbox = (left, upper, width, lower)
working_slice = img.crop(bbox)
upper += slice_size
#save the slice
working_slice.save(os.path.join(outdir, "slice_" + out_name + "_" + str(count)+".png"))
count +=1

if __name__ == '__main__':
#slice_size is the max height of the slices in pixels
long_slice("longcat.jpg","longcat", os.getcwd(), 300)

这是输出

Picture


Picture


Picture

关于python - 使用 Python Image Library 将一张图片切割成多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6059217/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com