0

I'm trying to rebuild a project using python, one step of it needs me downsample a two dimensions array into a smaller one.

Array like:

[[1.0, 2.0, 1.0, 3.0, ..., 2.0]
 [2.0, 4.0, 6.0, 8.0, ..., 3.0]
 ...
 [3.0, 1.0, 6.0, 2.0, ..., 9.0]]

(Just for example)

I want to downsample it into a smaller one but keeps its features. I'm not good at deep learning and just want to extend some conception from it. I tried padding array with zero outside (padding = 1), and convolution kernel size is 3x3. But I found this way cannot zoom array into smaller, so I change stride into 2 (Code: for j in range(1, EMatrix.shape[0]-1, 2)), but this caused new array contains some zero rows and columns, I don't know how to deal.

My code(part of it):

from shapely.geometry import box
from shapely.geometry import MultiPoint

import matplotlib.pyplot as plt

import numpy as np
import math
from sklearn import preprocessing

def Down_Sample(EMatrix):
    """
    Description: 

    Parameters: EMatrix (Type: 2-dim array)

    Return: 
    """

    # EMatrix = preprocessing.scale(EMatrix)
    EMatrix = np.pad(EMatrix, (1, 1), 'constant')
    DownSampleMatrix = np.empty((EMatrix.shape[0]-2, EMatrix.shape[1]-2), dtype=float)
    for j in range(1, EMatrix.shape[0]-1, 2):
        for i in range(1, EMatrix.shape[1]-1, 2):
            DownSampleMatrix[j-1][i-1] = max(EMatrix[j-1][i-1], EMatrix[j-1][i], EMatrix[j-1][i+1], \
                EMatrix[j][i-1], EMatrix[j][i], EMatrix[j][i+1], \
                EMatrix[j+1][i-1], EMatrix[j+1][i], EMatrix[j+1][i+1])


    return DownSampleMatrix

Left is origin array, Right is Downsampled array

I find an answer: Downsampling a 2d numpy array in python , but its approach seems not suit my scene.

Any way is ok, if there are ready method in sklearn or other packages.

P. Scotty
  • 55
  • 1
  • 6
  • I would expect exactly the second image if I were leaving every other row and column of the "downsampled" array unset! What do you mean _"this way cannot zoom array into smaller"_? If you want your downsampled array to be every other pixel from your original array, then the approach shown in the answer you've linked should work. Can you elaborate on why it doesn't work for you? – Pranav Hosangadi Mar 20 '23 at 15:21

0 Answers0