Skip to content

Instantly share code, notes, and snippets.

@VehpuS
Created June 2, 2022 09:49
Show Gist options
  • Save VehpuS/e66e4a605ec9ed0d4108d78864312073 to your computer and use it in GitHub Desktop.
Save VehpuS/e66e4a605ec9ed0d4108d78864312073 to your computer and use it in GitHub Desktop.
downsample a multiband image represented as a 3d numpy array (bands, height, width)
MASKED_VAL = -1 # Will depend on the band data (in my case it was always positive)
width = im.shape[-1]
height = im.shape[-2]
b = math.ceil(max(width, height)/factor)
dest_dim = b * factor
width_pad = dest_dim - width
height_pad = dest_dim - height
# Pad the array to a dimention that divides by the factor)
im = np.pad(im,
((0,0),
(height_pad // 2, math.ceil(height_pad / 2)),
(width_pad // 2, math.ceil(width_pad / 2))),
mode="constant", constant_values=(MASKED_VAL))
# Ignore the padded values when calculating the mean value for downsampling
im = im.reshape(im.shape[0], -1, factor, b, factor)
im = np.ma.masked_where(im == MASKED_VAL, im)
im[im == MASKED_VAL] = 0
# Downsampling can use other aggregation functions, i.e. sum / max / min / median
im = im.mean((-1, -3)) / factor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment