是否有更惯用的方式来显示图像网格,如下例所示?
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
和 reshape
等,但无法获得正确的行为。
我有兴趣使用 numpy 来执行此操作,因为使用 matplotlib 调用 subplot
和 imshow
可以绘制的图像数量有限。
如果您需要样本数据来测试,您可以像这样使用您的网络摄像头:
import cv2
import matplotlib.pyplot as plt
_, img = cv2.VideoCapture(0).read()
plt.imshow(gallery(np.array([img]*6)))
原文由 Frank Wilson 发布,翻译遵循 CC BY-SA 4.0 许可协议
产量
我们有一个形状数组
(nrows*ncols, height, weight, intensity)
。我们想要一个形状数组(height*nrows, width*ncols, intensity)
。所以这里的想法是首先使用
reshape
将第一个轴分成两个轴,一个长度nrows
和一个长度ncols
:这允许我们使用
swapaxes(1,2)
对轴重新排序,使形状变为(nrows, height, ncols, weight, intensity)
。 Notice that this placesnrows
next toheight
andncols
next towidth
.由于
reshape
不会更改数据的顺序,reshape(height*nrows, width*ncols, intensity)
现在生成所需的数组。这(在精神上)与
unblockshaped
函数 中使用的想法相同。