更多的自动方式在numpy网格中显示图像 [英] More idomatic way to display images in a grid with numpy

查看:120
本文介绍了更多的自动方式在numpy网格中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a more idiomatic way to display a grid of images as in the below example?

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

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

I tried using hstack and reshape etc, but could not get the right behaviour.

我有兴趣使用numpy来执行此操作,因为使用matplotlib调用 subplot imshow

I am interested in using numpy to do this because there is a limit to how many images you can plot with matplotlib calls to subplot and imshow.

如果您需要测试样本数据,可以使用您的网络我喜欢这样:

If you need sample data to test you can use your webcam like so:

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()

产生

我们有一个形状的数组(nrows * ncols,身高,体重,强度)
我们想要一个形状的数组(高度* nrows,宽度* ncols,强度)

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

So the idea here is to first use reshape to split apart the first axis into two axes, one of length nrows and one of length ncols:

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

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

This allows us to use swapaxes(1,2) to reorder the axes so that the shape becomes (nrows, height, ncols, weight, intensity). Notice that this places nrows next to height and ncols next to width.

重塑不会更改数据的raveled order reshape(height * nrows,width * ncols,intensity)现在生成所需的数组。

Since reshape does not change the raveled order of the data, reshape(height*nrows, width*ncols, intensity) now produces the desired array.

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

This is (in spirit) the same as the idea used in the unblockshaped function.

这篇关于更多的自动方式在numpy网格中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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