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
I tried using hstack
and reshape
etc, but could not get the right behaviour.
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)))