Skip to content

Instantly share code, notes, and snippets.

@kwinkunks
Created October 16, 2022 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwinkunks/4f7b1e734386d2cc4c64fc5bf4b8c17b to your computer and use it in GitHub Desktop.
Save kwinkunks/4f7b1e734386d2cc4c64fc5bf4b8c17b to your computer and use it in GitHub Desktop.
Reshape a 4D array into a image grid
"""
Given a 4D array of shape (n, h, w, c) representing n images of shape (h, w, c),
make a single image consisting of a regular grid of smaller images.
License: MIT No attribution
"""
import numpy as np
def reshape(arr, rows, cols, pixels=False):
"""Reshapes a 4D array into a grid of images.
See: https://stackoverflow.com/questions/58290692
Args:
arr (ndarray): The input data, shape (n, h, w, c) where n is the number
of examples, (h, w) is the shape of each image, and c is the number
of channels (usually 1, 3 or 4).
rows (int): The desired number of images or pixels in one column of the output.
cols (int): The desired number of images or pixels in one row of the output.
Returns:
ndarray.
Example:
>>> import numpy as np
>>> data = np.random.random((80, 8, 8, 3))
>>> data_new = reshape(data, rows=8, cols=10)
>>> data_new.shape
(64, 80, 3)
"""
n, h, w, c = arr.shape
if pixels:
rows, cols = rows // h, cols // w
arr_new = (arr.reshape(rows, cols, h, w, c)
.swapaxes(1, 2)
.reshape(h*rows, w*cols, c))
return arr_new
MIT No Attribution
Copyright 2022 Matt Hall, kwinkunks@GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment