How to downsample a matrix by keeping only one element every n*n blocks with numpy ?

Published: March 02, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Example of how to downsample a matrix by selecting only one element every $n \times n$ blocks with numpy:

Note: see also previous article how to do downsample a matrix by averaging elements n*n with numpy in python

Create a matrix

import numpy as np

a = np.random.randint(0,100,(6,6))

print(a)
print(a.shape)

returns for example

[[52 87 50 58 75 59]
 [27 40 36 50  9 20]
 [94 54  4  0  6  6]
 [ 5 50 87 74 36 93]
 [15 19  0 79 33 73]
 [51 57 32  8  1 89]]

with a shape of

(6, 6)

Keep only one element every $n \times n$ blocks

To downsample a matrix a simple solution is to slice the matrix, example:

a = a[1::2, 1::2]

print(a)
print(a.shape)

returns

[[40 50 20]
 [50 74 93]
 [57  8 89]]

with a shape of

(3, 3)

References