Fra*_*son 12 python numpy image-processing python-3.x
是否有更惯用的方式来显示图像网格,如下例所示?
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
Run Code Online (Sandbox Code Playgroud)
我试着用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)))
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 15
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()
Run Code Online (Sandbox Code Playgroud)
我们有一系列的形状(nrows*ncols, height, weight, intensity)
.我们想要一个形状的阵列(height*nrows, width*ncols, intensity)
.
所以这里的想法是首先使用reshape
将第一轴分成两个轴,一个是长度nrows
,另一个是长度ncols
:
array.reshape(nrows, ncols, height, width, intensity)
Run Code Online (Sandbox Code Playgroud)
这允许我们用来swapaxes(1,2)
重新排序轴,使形状变为
(nrows, height, ncols, weight, intensity)
.请注意,这位于nrows
旁边height
和ncols
旁边width
.
由于reshape
不改变数据的raveled顺序,reshape(height*nrows, width*ncols, intensity)
现在产生所需的数组.
这(在精神上)与unblockshaped
功能中使用的想法相同.
另一种方法是使用view_as_blocks。然后你避免手动交换轴:
from skimage.util import view_as_blocks
import numpy as np
def refactor(im_in,ncols=3):
n,h,w,c = im_in.shape
dn = (-n)%ncols # trailing images
im_out = (np.empty((n+dn)*h*w*c,im_in.dtype)
.reshape(-1,w*ncols,c))
view=view_as_blocks(im_out,(h,w,c))
for k,im in enumerate( list(im_in) + dn*[0] ):
view[k//ncols,k%ncols,0] = im
return im_out
Run Code Online (Sandbox Code Playgroud)