More idiomatic way to display images in a grid with numpy

后端 未结 3 1477
青春惊慌失措
青春惊慌失措 2020-12-31 09:40

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(         


        
3条回答
  •  太阳男子
    2020-12-31 10:01

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

    yields


    We have an array of shape (nrows*ncols, height, weight, intensity). We want an array of shape (height*nrows, width*ncols, intensity).

    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)
    

    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.

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

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

提交回复
热议问题