gpt4 book ai didi

python - 使用 numpy 在网格中显示图像的更惯用方式

转载 作者:太空狗 更新时间:2023-10-29 18:00:01 24 4
gpt4 key购买 nike

是否有更惯用的方式来显示图像网格,如下例所示?

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

我尝试使用 hstackreshape 等,但无法获得正确的行为。

我对使用 numpy 来执行此操作很感兴趣,因为使用 matplotlib 调用 subplotimshow 可以绘制的图像数量是有限制的。

如果您需要样本数据进行测试,您可以像这样使用您的网络摄像头:

import cv2
import matplotlib.pyplot as plt
_, img = cv2.VideoCapture(0).read()

plt.imshow(gallery(np.array([img]*6)))

最佳答案

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

产量 enter image description here


我们有一个形状数组(nrows*ncols, height, weight, intensity)。我们想要一个形状为 (height*nrows, width*ncols, intensity) 的数组。

所以这里的想法是首先使用reshape将第一个轴分成两个轴,一个长度为nrows,一个长度为ncols:

array.reshape(nrows, ncols, height, width, intensity)

这允许我们使用 swapaxes(1,2) 重新排序轴,使形状变为(nrows,height,ncols,weight,intensity)。请注意,这会将 nrows 放在 height 旁边,将 ncols 放在 width 旁边。

reshape does not change the raveled order数据的 reshape(height*nrows, width*ncols, intensity) 现在生成所需的数组。

这(在精神上)与 unblockshaped function 中使用的想法相同.

关于python - 使用 numpy 在网格中显示图像的更惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42040747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com