python - 使用 numpy 在网格中显示图像的更惯用方式

标签 python python-3.x numpy image-processing

是否有更惯用的方式来显示图像网格,如下例所示?

import numpy as np

def gallery(array, ncols=3):
    nrows = np.math.ceil(len(array)/float(ncols))
    cell_w = array.shape[2]
    cell_h = array.shape[1]
    channels = array.shape[3]
    result = np.zeros((cell_h*nrows, cell_w*ncols, channels), dtype=array.dtype)
    for i in range(0, nrows):
        for j in range(0, ncols):
            result[i*cell_h:(i+1)*cell_h, j*cell_w:(j+1)*cell_w, :] = array[i*ncols+j]
    return result

我尝试使用 hstackreshape 等,但无法获得正确的行为。

我对使用 numpy 来执行此操作很感兴趣,因为使用 matplotlib 调用 subplotimshow 可以绘制的图像数量是有限制的。

如果您需要样本数据进行测试,您可以像这样使用您的网络摄像头:

import cv2
import matplotlib.pyplot as plt
_, img = cv2.VideoCapture(0).read()

plt.imshow(gallery(np.array([img]*6)))

最佳答案

import numpy as np
import matplotlib.pyplot as plt

def gallery(array, ncols=3):
    nindex, height, width, intensity = array.shape
    nrows = nindex//ncols
    assert nindex == nrows*ncols
    # want result.shape = (height*nrows, width*ncols, intensity)
    result = (array.reshape(nrows, ncols, height, width, intensity)
              .swapaxes(1,2)
              .reshape(height*nrows, width*ncols, intensity))
    return result

def make_array():
    from PIL import Image
    return np.array([np.asarray(Image.open('face.png').convert('RGB'))]*12)

array = make_array()
result = gallery(array)
plt.imshow(result)
plt.show()

产量 enter image description here


我们有一个形状数组(nrows*ncols, height, weight, intensity)。 我们想要一个形状为 (height*nrows, width*ncols, intensity) 的数组。

所以这里的想法是首先使用reshape将第一个轴分成两个轴,一个长度为nrows,一个长度为ncols:

array.reshape(nrows, ncols, height, width, intensity)

这允许我们使用 swapaxes(1,2) 重新排序轴,使形状变为 (nrows,height,ncols,weight,intensity)。请注意,这会将 nrows 放在 height 旁边,将 ncols 放在 width 旁边。

reshape does not change the raveled order数据的 reshape(height*nrows, width*ncols, intensity) 现在生成所需的数组。

这(在精神上)与 unblockshaped function 中使用的想法相同.

关于python - 使用 numpy 在网格中显示图像的更惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42040747/

相关文章:

python - 如何将类别矩阵可视化为 RGB 图像?

python - 在 Pandas 时间序列中,如何为每一行获取延迟到期前的最后一个值?

python - 如何将 python 的 "import this"作为字符串返回?

Python - 计算空格,而不是空行

python-3.x - 如何用其他内容替换数据帧列的每个 "elements"的一部分

python - 如何在线程之间共享对象?

python - 如何从 sitecustomize.py 获取脚本的名称/文件?

python - 如何通过 3D 点云拟合一条线?

python - 如何为py.test设置动态默认参数?

python - 使用 Python 仅将 HDF5 文件中的部分数据加载到内存中