【问题标题】:python numpy image arrays: Take a list of horizontally concatenated images and arrange them in a gridpython numpy图像数组:获取水平连接图像的列表并将它们排列在网格中
【发布时间】:2021-02-18 01:10:11
【问题描述】:

我正在尝试从源文件夹中获取图像列表并将它们放在一个 2x2 网格中,每个图像下方都有一些文本。

到目前为止,我的代码可以扫描文件夹,在每个图像下添加适当的文本,添加边框,并在一行中显示图像,为简洁起见,我将省略这些。我把它们都做成一条线,因为后来我想把它扩展到更大的网格大小,所以我的理论是所有图像都变成一条大线,然后再分类成一个网格:

这行图像是一个 numpy 数组,像这样连接在一起:

images_line = np.hstack( (np.asarray(i) for i in list_images_with_text ) )

print(images.ndim)  > 3
print(images.size)  > 1326000
print(images.shape) > (325, 1360, 3)

我已经尝试过 numpy 的 images.reshape() 来获取数组并将其转换为 2x2 的图像网格,即:

阿西莫夫末日

敦刻尔克金属乐队

single_width = horiz_img_size;
single_height = vert_img_size + info_box_height;
images = images.reshape(2*single_height,2*single_width,3)

但这并不完全正确:

我觉得我很接近了,但我无法完全理解 3d 数组。我想将此扩展到更多的网格尺寸,4x4、5x5、5x4 等。如果可能,用户可输入。

如果您下载原始图像,这是一个最小的可重现示例

import numpy as np
import glob
import PIL
from PIL import Image

single_width = 340
single_height = 325

im=Image.open('TDYZ0.jpg')
images = np.asarray(im)

images = images.reshape(2*single_height,2*single_width,3) # not quite right

images = PIL.Image.fromarray(images)
images.save('outImage.png')    

谢谢大家

【问题讨论】:

  • 如果您希望它可扩展,您可能希望保留您的图像列表[np.asarray(i) for i in list_images_with_text],然后使用np.block 玩弄它们
  • 谢谢,我设法通过以下方式得到了我想要的,但我不知道如何使它可扩展/可循环images = np.block([[[list_images_with_text[0]],[list_images_with_text[1]]],[[list_images_with_text[2]],[list_images_with_text[3]]]])

标签: python arrays image numpy 3d


【解决方案1】:

对于图像的 MxN 平铺,也许您可​​以尝试(我尚未测试):

images = images.reshape(M, N, single_height, single_width, 3)

因此,对于您显示输出的 2x2,它将是:

images = images.reshape(2, 2, single_height, single_width, 3)

【讨论】:

  • 感谢您的回复,我在这里得到了一个 (2,2,325,340,3) 的 5d 数组,PIL.Image.fromarray(images) 不知道如何处理。我不确定从这里做什么
  • @WillHaward -- 我现在意识到理解PIL.Image.fromarray() 在这里很重要 -- 我根本没有。例如,一个相关的问题是 - fromarray() 是否只期望 h x w 图像的一维数组,或者它是否也接受 h x w 图像的 M x N 数组?祝你好运。
【解决方案2】:

我解决了它,尽管是以一种令人作呕的方式。构建一个字符串以形成 np.block() 命令的正确层次结构,然后执行。基于 Daniel F 的评论:

M = 2
N = 2
string = "images = np.block([["
maxpos = numfiles-1;
pos = 0;
try:
    for j in range(0, N):
        for i in range(0, M):
            if pos > maxpos:
                string+= f"[np.asarray(null_image)],"
            else:
                string += f"[list_images_with_text[{pos}]]"
                pos=pos+1
                if i < M-1:
                    string+=f","
        if j < N-1:
            string+=f"],["
    string+="]])"
except:
   print("oops")
exec(string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 2020-12-28
    相关资源
    最近更新 更多