import numpy as np
import scipy.ndimage
def ndarray_zoom_scaling(label, new_h, new_w):
"""
Implement scaling for ndarray with scipy.ndimage.zoom
:param label: [H, W] or [H, W, C]
:return: label_new: [new_h, new_w] or [new_h, new_w, C]
Examples
--------
ori_arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=np.int32)
new_arr = ndarray_zoom_scaling(ori_arr, new_h=8, new_w=10)
>> print(new_arr)
[[1 1 1 2 2 2 2 3 3 3]
[1 1 1 2 2 2 2 3 3 3]
[4 4 4 5 5 5 5 6 6 6]
[4 4 4 5 5 5 5 6 6 6]
[4 4 4 5 5 5 5 6 6 6]
[4 4 4 5 5 5 5 6 6 6]
[7 7 7 8 8 8 8 9 9 9]
[7 7 7 8 8 8 8 9 9 9]]
"""
scale_h = new_h / label.shape[0]
scale_w = new_w / label.shape[1]
if len(label.shape) == 2:
label_new = scipy.ndimage.zoom(label, zoom=[scale_h, scale_w], order=0)
else:
label_new = scipy.ndimage.zoom(label, zoom=[scale_h, scale_w, 1], order=0)
return label_new
def ndarray_nearest_neighbour_scaling(label, new_h, new_w):
"""
Implement nearest neighbour scaling for ndarray
:param label: [H, W] or [H, W, C]
:return: label_new: [new_h, new_w] or [new_h, new_w, C]
Examples
--------
ori_arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=np.int32)
new_arr = ndarray_nearest_neighbour_scaling(ori_arr, new_h=8, new_w=10)
>> print(new_arr)
[[1 1 1 1 2 2 2 3 3 3]
[1 1 1 1 2 2 2 3 3 3]
[1 1 1 1 2 2 2 3 3 3]
[4 4 4 4 5 5 5 6 6 6]
[4 4 4 4 5 5 5 6 6 6]
[4 4 4 4 5 5 5 6 6 6]
[7 7 7 7 8 8 8 9 9 9]
[7 7 7 7 8 8 8 9 9 9]]
"""
if len(label.shape) == 2:
label_new = np.zeros([new_h, new_w], dtype=label.dtype)
else:
label_new = np.zeros([new_h, new_w, label.shape[2]], dtype=label.dtype)
scale_h = new_h / label.shape[0]
scale_w = new_w / label.shape[1]
y_pos = np.arange(new_h)
x_pos = np.arange(new_w)
y_pos = np.floor(y_pos / scale_h).astype(np.int32)
x_pos = np.floor(x_pos / scale_w).astype(np.int32)
y_pos = y_pos.reshape(y_pos.shape[0], 1)
y_pos = np.tile(y_pos, (1, new_w))
x_pos = np.tile(x_pos, (new_h, 1))
assert y_pos.shape == x_pos.shape
label_new[:, :] = label[y_pos[:, :], x_pos[:, :]]
return label_new