Skip to content

Instantly share code, notes, and snippets.

@andrewgiessel
Created June 19, 2012 18:19
Show Gist options
  • Save andrewgiessel/2955714 to your computer and use it in GitHub Desktop.
Save andrewgiessel/2955714 to your computer and use it in GitHub Desktop.
downsample code
def downsample2d(inputArray, kernelSize):
"""This function downsamples a 2d numpy array by convolving with a flat
kernel and then sub-sampling the resulting array.
A kernel size of 2 means convolution with a 2x2 array [[1, 1], [1, 1]] and
a resulting downsampling of 2-fold.
:param: inputArray: 2d numpy array
:param: kernelSize: integer
"""
average_kernel = np.ones((kernelSize,kernelSize))
blurred_array = sig.convolve2d(inputArray, average_kernel, mode='same')
downsampled_array = blurred_array[::kernelSize,::kernelSize]
return downsampled_array
def downsample3d(inputArray, kernelSize):
"""This function downsamples a 3d numpy array (an image stack)
by convolving each frame with a flat kernel and then sub-sampling the resulting array,
re-building a smaller 3d numpy array.
A kernel size of 2 means convolution with a 2x2 array [[1, 1], [1, 1]] and
a resulting downsampling of 2-fold.
The array will be downsampled in the first 2 dimensions, as shown below.
import numpy as np
>>> A = np.random.random((100,100,20))
>>> B = downsample3d(A, 2)
>>> A.shape
(100, 100, 20)
>>> B.shape
(50, 50, 20)
:param: inputArray: 2d numpy array
:param: kernelSize: integer
"""
first_smaller = downsample2d(inputArray[:,:,0], kernelSize)
smaller = np.zeros((first_smaller.shape[0], first_smaller.shape[1], inputArray.shape[2]))
smaller[:,:,0] = first_smaller
for i in range(1, inputArray.shape[2]):
smaller[:,:,i] = downsample2d(inputArray[:,:,i], kernelSize)
return smaller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment