2017-02-04 1 views
6

次の例のように画像のグリッドを表示する方法はもっと慣れていますか?numpyを使ってグリッドに画像を表示する方法がもっと便利

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などを使用してみましたが、右の振る舞いを得ることができませんでした。

matplotlibでプロットできる画像の数がsubplotimshowに制限されているため、numpyを使用することに興味があります。

あなたがテストするためのサンプルデータが必要な場合には、そのようなあなたのウェブカメラを使用することができます。

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

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

'配列'の形は何ですか? – Divakar

+0

4つの次元(インデックス、行、列、強度)。どこの強度= 3です。 –

+0

私はそれを実行することはできません。サンプルを投稿して、最後にテストしてもらえますか? – Divakar

答えて

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

は、我々は形状(nrows*ncols, height, weight, intensity)の配列を持っている enter image description here


が得られます。 形状の配列(height*nrows, width*ncols, intensity)が必要です。これは、私たちは軸を並べ替えるswapaxes(1,2)を使用することができます

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

だからここでの考え方は、最初の2つの軸、長さnrowsの1と長さncolsの一つに第一の軸を離れて分割するreshapeを使用することですその形状は (nrows, height, ncols, weight, intensity)となる。これは、heightncolsの隣にwidthの隣にnrowsが配置されていることに注目してください。

reshape does not change the raveled orderのデータのため、reshape(height*nrows, width*ncols, intensity)は現在、目的の配列を生成します。

これは、unblockshaped functionで使用されている考えと同じです。

3

もう1つの方法はview_as_blocksです。

from skimage.util import view_as_blocks 

def refactor(im_in,ncols=3): 
    n,h,w,c = im_in.shape 
    dn = (-n)%ncols # trailing images 
    im_out = (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 
関連する問題