Python: Shrink/Extend 2D arrays in fractions -
Python: Shrink/Extend 2D arrays in fractions -
there 2d arrays
of numbers outputs of numerical processes in form of 1x1, 3x3, 5x5, ...
shaped, correspond different resolutions.
in stage average i.e., 2d array value in shape nxn
needs produced. if outputs in consistency of shape i.e., in 11x11
solution obvious, so:
element_wise_mean_of_all_arrays
.
for problem of post arrays in different shapes obvious way not work!
i thought might help using kron
function didn't. example, if array in shape of 17x17
how create 21x21
. others 1x1
,3x3
,..., build constant-shaped array, 21x21
. can case arrays smaller , bigger in shape compared target shape. array of 31x31
shruk 21x21
.
you imagine problem mutual task images, beingness shrunk or extended.
what possible efficient approaches same jobs on 2d
arrays, in python, using numpy, scipy, etc?
updates: here bit optimized version of accepted reply bellow:
def resize(x,shape=none): if shape==none: homecoming x m,n = shape y = np.zeros((m,n),dtype=type(x[0,0])) k = len(x) p,q = k/m,k/n in xrange(m): y[i,:] = x[i*p,np.int_(np.arange(n)*q)] homecoming y
it works perfectly, agree the best choice in terms of efficiency? if not improvement?
# expanding --------------------------------- >>> x = np.array([[1,2,3],[4,5,6],[7,8,9]]) [[1 2 3] [4 5 6] [7 8 9]] >>> resize(x,[7,11]) [[1 1 1 1 2 2 2 2 3 3 3] [1 1 1 1 2 2 2 2 3 3 3] [1 1 1 1 2 2 2 2 3 3 3] [4 4 4 4 5 5 5 5 6 6 6] [4 4 4 4 5 5 5 5 6 6 6] [7 7 7 7 8 8 8 8 9 9 9] [7 7 7 7 8 8 8 8 9 9 9]] # shrinking --------------------------------- >>> x = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> resize(x,(2,2)) [[ 1 3] [ 9 11]]
final note: code above translated fortran
highest performance possible.
i'm not sure understand trying if think simplest way be:
wanted_size = 21 = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) b = numpy.zeros((wanted_size, wanted_size)) in range(wanted_size): j in range(wanted_size): idx1 = * len(a) / wanted_size idx2 = j * len(a) / wanted_size b[i][j] = a[idx1][idx2]
you maybe replace b[i][j] = a[idx1][idx2] custom function average of 3x3 matrix centered in a[idx1][idx2] or interpolation function.
python multidimensional-array shrink
Comments
Post a Comment