Downsampling a 2d numpy array in python


I’m self learning python and have found a problem which requires down sampling a feature vector. I need some help understanding how down-sampling a array. in the array each row represents an image by being number from 0 to 255. I was wonder how you apply down-sampling to the array? I don’t want to scikit-learn because I want to understand how to apply down-sampling.
If you could explain down-sampling too that would be amazing thanks.

the feature vector is 400×250

Asked By: Neo Streets



If with downsampling you mean something like this, you can simply slice the array. For a 1D example:

import numpy as np
a = np.arange(1,11,1)

The last line is equivalent to:


with the slicing notation as start:stop:step


[ 1 2 3 4 5 6 7 8 9 10]

[ 1 4 7 10]

For a 2D array the idea is the same:

b = np.arange(0,100)
c = b.reshape([10,10])

This gives you, in both dimensions, every third item from the original array.

Or, if you only want to down sample a single dimension:

d = np.zeros((400,250))
e = d[::10,:]

(400, 250)

(40, 250)

The are lots of other examples in the Numpy manual

Answered By: Bart
from skimage.measure import block_reduce

b = block_reduce(matrix, block_size=(m, n), func=np.mean/np.max/..)
Answered By: Md. Monirul Islam

from skimage.measure import block_reduce

Answered By: Md. Monirul Islam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.