将目录中的多个不同图像合并到大小为3x6的画布中 [英] Combine multiple different images from a directory into a canvas sized 3x6

查看:64
本文介绍了将目录中的多个不同图像合并到大小为3x6的画布中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要查看目录的图像.我想从这些图像中创建一个3x6画布,一个新图像将把该目录的图像并排显示为一个图像/画布.每个图像必须是不同的图像.并排. –

I itirate to images of a directory. I want from those images to create a 3x6 canvas, a new image that will display the images of that directory side by side into a single image / canvas. Each image must be a different image. Side by side. –

我有以下代码.它尝试从存储在列表中的目录中读取图像文件名.然后,它尝试将每个图像复制/合并到一个3x6的画布中.但是,我想要的结果不会发生. 我做错了什么?

I have the following code. It tries to read the image filenames from a directory that are stored into a list. Then it tries to copy / combine each image into a 3x6 canvas. However, the result that i want happens not. What i am doing wrong?

import Image
import os
import PIL
import glob
import matplotlib.pyplot as plt

# path
path = "/media/"
listing = os.listdir(path)

# getting all path+filename in a list
npath=[]
im=[]
for infile in listing:
  im.append(infile)
  npath.append(os.path.join(path, infile))

#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (2100,2400))


#Here I resize my opened image, so it is no bigger than ****
#Iterate through a grid with some spacing, to place my image
for i in xrange(0,2100,700):
    for j in xrange(0,2400, 400):
        for imagefile in npath:
            im=Image.open(imagefile)
            im.thumbnail((1000,1000))
            #paste the image at location i,j:
            new_im.paste(im, (i,j))
            new_im.show()
#saving
new_im.save('/media/test.png')

解决方案

import Image
import os
import PIL
import glob
import matplotlib.pyplot as plt

# path
path = "/media/"
listing = os.listdir(path)


# getting all path+filename in a list
npath=[]
im=[]

for infile in listing:
  im.append(infile)
  npath.append(os.path.join(path, infile))

#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (2500,3000))

for i in xrange(0,2500,800):
    for j in xrange(0,3000, 500):
        im=Image.open(npath.pop(0))
        im.thumbnail((1000,1000))
        #paste the image at location i,j:
        new_im.paste(im, (i,j))
    new_im.save('/media/test.png')

推荐答案

不要在每个位置上重复图像列表,而要使用该列表:

Do not iterate over the image list for every position, consume the list instead:

for i in xrange(0, 2100, 700):
    for j in xrange(0, 2400, 400):
        try:
            filepath = npath.pop(0)
        except IndexError:
            break
        im = Image.open(filepath)
        im.thumbnail((1000,1000))
        # paste the image at location i,j
        new_im.paste(im, (i,j))
    else:
        continue  # executed if inner loop ended normally (no break)
    break  # executed if 'continue' was skipped (break occurred)

这篇关于将目录中的多个不同图像合并到大小为3x6的画布中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆