Skip to content

Instantly share code, notes, and snippets.

@arenaudineau
Last active July 20, 2023 08:32
Show Gist options
  • Save arenaudineau/0172f205b4ed8091786d6209b3601faf to your computer and use it in GitHub Desktop.
Save arenaudineau/0172f205b4ed8091786d6209b3601faf to your computer and use it in GitHub Desktop.
Python function to conveniently resize an image and preserve pixel size. This was found useful to change extent for plt.imshow
from typing import Any, Tuple
def resize_img(img: np.ndarray, extent_from: Tuple[int, int, int, int], extent_to: Tuple[int, int, int, int], fill_value: Any = 0):
"""
Resize an image to a new extent, keeping the pixels size.
The image is cropped if the new extent is smaller than the old one.
The image is padded with fill_value if the new extent is larger than the old one.
Parameters:
img (numpy.ndarray): Input image as a NumPy array.
extent_from (tuple): Tuple (left, right, top, bottom) representing the current extent of the image.
extent_to (tuple): Tuple (left, right, top, bottom) representing the desired extent of the image.
fill_value (Any, optional): The value used for padding. Defaults to 0.
Returns:
numpy.ndarray: Resized image as a NumPy array.
"""
if not isinstance(img, np.ndarray):
raise ValueError("Input 'img' must be a NumPy array.")
if len(extent_from) != 4 or len(extent_to) != 4:
raise ValueError("Both 'extent_from' and 'extent_to' must be tuples of length 4.")
px_w = (extent_from[1] - extent_from[0]) / img.shape[1]
px_h = (extent_from[3] - extent_from[2]) / img.shape[0]
# Calculate the number of pixels to pad/crop.
# Positive values mean *pad*.
# Negative values mean *crop*.
dtop = int((extent_from[2] - extent_to[2]) / px_h)
dbot = int((extent_to[3] - extent_from[3]) / px_h)
dleft = int((extent_from[0] - extent_to[0]) / px_w)
dright = int((extent_to[1] - extent_from[1]) / px_w)
img = img[
max(0, -dtop):img.shape[0] - max(0, -dbot),
max(0, -dleft):img.shape[1] - max(0, -dright)
]
return np.pad(img,
(
(max(0, dtop), max(0, dbot)),
(max(0, dleft), max(0, dright))
),
constant_values=fill_value,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment