Python图像库:如何将4张图像组合成2 x 2网格? [英] Python Image Library: How to combine 4 images into a 2 x 2 grid?
问题描述
我有4个带有动画图像的目录.我想拍摄一组图像,并生成4张图像的单个图像,并按动画的每一帧将它们排列成2x2的网格.
I have 4 directories with images for an animation. I would like to take the set of images and generate a single image with the 4 images arranged into a 2x2 grid for each frame of the animation.
到目前为止,我的代码是:
My code so far is:
import Image
fluid64 = "Fluid64_half_size/00"
fluid128 = "Fluid128_half_size/00"
fluid512 = "Fluid512_half_size/00"
fluid1024 = "Fluid1024_half_size/00"
out_image = "Fluid_all/00"
for pic in range(1, 26):
blank_image = Image.open("blank.jpg")
if pic < 10:
image_num = "0"+str(pic)
else:
image_num = str(pic)
image64 = Image.open(fluid64+image_num+".jpg")
image128 = Image.open(fluid128+image_num+".jpg")
image512 = Image.open(fluid512+image_num+".jpg")
image1024 = Image.open(fluid1024+image_num+".jpg")
out = out_image + image_num + ".jpg"
blank_image.paste(image64, (0,0)).paste(fluid128, (400,0)).paste(fluid512, (0,300)).paste(fluid1024, (400,300)).save(out)
不知道为什么它不起作用.我遇到了错误:
Not sure why it's not working. I'm getting the error:
Traceback (most recent call last):
File "C:\Users\Casey\Desktop\Image_composite.py", line 24, in <module>
blank_image.paste(image64, (0,0)).paste(fluid128, (400,0)).paste(fluid512, (
ste(fluid1024, (400,300)).save(out)
AttributeError: 'NoneType' object has no attribute 'paste'
shell returned 1
任何帮助都会很棒.谢谢!
Any help would be awesome. Thanks!
推荐答案
唯一的问题是粘贴"不返回图像对象-而是就地修改了空白"图像.
The only problem there is that "paste" does not return an image object - it rather modifies the "blank" image inplace.
因此,当调用第二个粘贴(使用fuild128图像的粘贴)时,它将尝试应用到无"(None)上-这是第一个图像的返回值.
So, when the second paste is called (the one that uses the fuild128 image), it tries to be applied on "None" - which is the return value of the first image.
如果这是您唯一的问题,只需每行进行一次粘贴调用,如下所示:
If that is the only problem you are having, just make one paste call per line, like this:
blank_image.paste(image64, (0,0))
blank_image.paste(fluid128, (400,0))
blank_image.paste(fluid512, (0,300))
blank_image.paste(fluid1024, (400,300))
blank_image.save(out)
尽管看起来您可能需要缩放每个图像,以便它们的格式也匹配. 而且,"image_num"变量的代码是不必要的. Python非常适合使用字符串-只需执行以下操作即可:
Although it looks likely you'd need to scale each image so that their format match as well. And your code for the "image_num" variable is unecessary. Python is really good with strings - just do something like this:
image64 = Image.open(fluid64 + "%02d.jpg" % pic)
这篇关于Python图像库:如何将4张图像组合成2 x 2网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!