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