用Python水平连接图像
水平组合多个图像是图像处理中的常见任务。 Python 提供了强大的工具来使用 Pillow 库来实现此目的。
问题描述
考虑三个尺寸为 148 x 95 的方形 JPEG 图像。目标是水平连接这些图像图像,同时避免结果输出中出现任何部分图像。
建议的解决方案
以下代码片段解决了该问题:
import sys
from PIL import Image
# Get the images
images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
# Determine the total width and height
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
# Create a new, empty image
new_im = Image.new('RGB', (total_width, max_height))
# Paste the images horizontally
x_offset = 0
for im in images:
new_im.paste(im, (x_offset, 0))
x_offset = im.size[0]
# Save the output image
new_im.save('test.jpg')
此代码迭代输入图像,确定它们的尺寸。它创建一个具有所有图像的总宽度和最大高度的新图像。每个输入图像都是水平粘贴的,并且它们的位置也会相应更新。
其他注意事项
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3