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

标签 python numpy python-imaging-library opencv-python

我有一个问题。比如我有3张图片(50x50px),我需要将这些图片合成一张图片(比如输出为500x500px)。我的问题是每次水平填充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))

最佳答案

你是说这样吗?

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)

关于python - 将许多小图像连接成一个大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60597402/

相关文章:

python - Pandas Dataframe 列的条件计算

python - 从字符串的开头删除 n 个字符

Python - 查找第一个和最后一个白色像素坐标

python - 从插值函数中检索值

python - 为什么使用 PIL 保存为 pdf 会在字体周围产生灰色区域

python - PIL : How to reopen an image after verifying?

python - Django:检查图像是否存在于某个特定的 url

python - 使用索引循环的最快方法

python - 如何加快应用两个二维数组的 scipy 集成?

python - 使用 Python 重叠 2 个 RGBA 图像