gpt4 book ai didi

python - 在 Python 中合并图像

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:48 25 4
gpt4 key购买 nike

如果两个图像大小相等,我正在尝试将它们合并在一起。有人可以帮我吗?这就是我到目前为止所得到的......

import PIL
from PIL import Image as img
x = img.open('index.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('index2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if x.size == y.size :
print('Their size is equal.')
height = max(h1,h2)
width = w1 + w2
z = img.new("RGB",(width,height))
z.paste(x)
#z.paste(y)
z.show()

else:
print('Their size is not equal.')

如何将第二张图像粘贴到第一张图像旁边?

最佳答案

.paste(..)函数允许您指定 box 参数来指定位置。

因此,您可以粘贴第二张图像:

import PIL
from PIL import Image as img
x = img.open('img1.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('img2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if x.size == y.size :
print('Their size is equal.')
z = img.new("RGB",(w1 + w2,h1))
z.paste(x)
z.paste(y<b>, box=(w1, 0)</b>)
z.show()
else:
print('Their size is not equal.')

请注意,由于尺寸相等,因此高度仅为 h1

您可以放宽尺寸的限制,因为如果高度相同,这也可以工作,只是如果宽度不同,图像不会分成两半:

import PIL
from PIL import Image as img
x = img.open('img1.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('img2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if <b>h1 == h2</b>:
print('Their size is equal.')
z = img.new("RGB",(w1 + w2,h1))
z.paste(x)
z.paste(y, box=(w1, 0))
z.show()
else:
print('Their size is not equal.')

关于python - 在 Python 中合并图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56818344/

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