More idiomatic way to display images in a grid with numpy

后端 未结 3 1450
青春惊慌失措
青春惊慌失措 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 09:59

    This answer is based off @unutbu's, but this deals with HWC ordered tensors. Furthermore, it shows black tiles for any channels that do not factorize evenly into the given rows/columns.

    def tile(arr, nrows, ncols):
        """
        Args:
            arr: HWC format array
            nrows: number of tiled rows
            ncols: number of tiled columns
        """
        h, w, c = arr.shape
        out_height = nrows * h
        out_width = ncols * w
        chw = np.moveaxis(arr, (0, 1, 2), (1, 2, 0))
    
        if c < nrows * ncols:
            chw = chw.reshape(-1).copy()
            chw.resize(nrows * ncols * h * w)
    
        return (chw
            .reshape(nrows, ncols, h, w)
            .swapaxes(1, 2)
            .reshape(out_height, out_width))
    

    Here's a corresponding detiling function for the reverse direction:

    def detile(arr, nrows, ncols, c, h, w):
        """
        Args:
            arr: tiled array
            nrows: number of tiled rows
            ncols: number of tiled columns
            c: channels (number of tiles to keep)
            h: height of tile
            w: width of tile
        """
        chw = (arr
            .reshape(nrows, h, ncols, w)
            .swapaxes(1, 2)
            .reshape(-1)[:c*h*w]
            .reshape(c, h, w))
    
        return np.moveaxis(chw, (0, 1, 2), (2, 0, 1)).reshape(h, w, c)
    

提交回复
热议问题