A clearer way to display images in a grid with numpy

Is there a more idiomatic way to display an image grid, as in the example below?

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 hstackand reshapeso on, but could not get the correct behavior.

I am interested in using numpy for this, because there is a limit to how many images you can build using matplotlib calls on subplotand imshow.

If you need sample data for testing, you can use your webcam as follows:

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

plt.imshow(gallery(np.array([img]*6)))
+10
source share
2 answers
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()

gives 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 , reshape(height*nrows, width*ncols, intensity) .

( ) , , unblockshaped .

+12

- 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
+4

Source: https://habr.com/ru/post/1014698/


All Articles