将许多小图像连接成一个大图像

3

我有一个问题,例如,我有三张50x50像素的图片,我需要将这些图片合并成一张图片(例如,输出为500x500像素)。我的问题是,我不知道如何在每次水平填充3个图像时垂直合并它们。现在我只知道如何填充两行(一次水平和一次垂直)。如果您能帮助我,我将感到高兴。谢谢!下面是可以实现我所需功能的代码,但我还想能够调整图像以适应新的行或列:

img = 'path_to_image'
new_im = Image.new('RGB', (400, 400))
for x in range(0, 400, img.width):
    for y in range(0, 400, img.height):
        new_im.paste(img, (x, y))

你不能这么轻易地愚弄我 - 我知道3x50不等于500!!! - Mark Setchell
我的意思是它们需要被组合在一起,直到输出图像。 - Paladond
1个回答

0

您的意思是这样吗?

import numpy as np
img_1 = np.ones((2, 2))
img_2 = np.ones((2, 2)) * 2
img_3 = np.ones((2, 2)) * 3

img = np.hstack([img_1, img_2, img_3])
# array([[1., 1., 2., 2., 3., 3.],
#        [1., 1., 2., 2., 3., 3.]])

new_shape = np.array([6, 12])
new_img = np.tile(img, reps=new_shape // np.array(img.shape))
# array([[1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.],
#        [1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.], 
#        [1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.],
#        [1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.],
#        [1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.],
#        [1., 1., 2., 2., 3., 3., 1., 1., 2., 2., 3., 3.]])

如果您想要调整图像大小,也许this answer可以帮到您。

这种方法不关心您如何获取img。重要的是,您必须确保所有初始图像的组合将添加到最终形状。

如果您有形状为50x50的图像和最终形状为500x500,并且您总是将它们中的2、3或4个组合在一起,则会出现以下情况:

  • 500 / (2*50) = 5
  • 500 / (3*50) = 3.33
  • 500 / (4*50) = 2.5

所以这对您来说行不通。 您有两个选择,要么裁剪不适合的像素,要么调整结果图像的大小。

  • 500 / (2*50) = 5
  • 500 / (3*50) = 3.33 -> 4,将500x600的图像裁剪/缩放为500x500
  • 500 / (4*50) = 2.5 -> 3,将500x600的图像裁剪/缩放为500x500
import numpy as np
img_1 = np.ones((2, 2))
img_2 = np.ones((2, 2)) * 2
img_3 = np.ones((2, 2)) * 3
img_4 = np.ones((2, 2)) * 4
img_list = np.array([img_1, img_2, img_3, img_4])

# Get random combination of 2-4 images
img_dx_rnd = np.random.choice(np.arange(4), np.random.randint(2, 5), replace=False)
img = np.hstack([*img_list[img_dx_rnd]])

new_shape = np.array([6, 12])
reps = np.ceil(new_shape / np.array(img.shape)).astype(int)
new_img = np.tile(img, reps=reps)

# Cropping
new_img = new_img[:new_shape[0], :new_shape[1]]

# Resizing
from skimage.transform import resize
new_img = resize(new_img, new_shape)

我添加了一个调整图像大小的链接。那么你想看什么?你能再解释一下你想要实现什么吗? - scleronomic
我可以有2、3或4张小图片 - 这并不重要。我需要将它们制作成一个输出图像(例如500x500像素)。但是每次从列表中随机选择小图像并连接起来。 - Paladond
我编辑了我的回答,我想现在我更好地理解了你的问题。这是裁剪/调整大小的问题吗? - scleronomic
我可以通过电子邮件与您联系,以便更详细地讨论任务吗? - Paladond

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接