-1

Suppose we have a 6x6 matrix (numpy ndarray) like:

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

How would I calculate the mean value of each of the 2x2 submatrices containing the same number, and get as an output a 3x3 matrix?

smci
  • 32,567
  • 20
  • 113
  • 146
sdaste
  • 11
  • 1
  • 1
    How is your 6x6 matrix formatted? Is it a list of 36 elements? Is it a numpy array? Please give more details. – Aplet123 Nov 09 '20 at 23:10
  • it is a numpy.ndarray! – sdaste Nov 09 '20 at 23:15
  • 1
    Related: https://stackoverflow.com/questions/14406567/paritition-array-into-n-chunks-with-numpy Once you have chunks, finding the mean is trivial. – Pranav Hosangadi Nov 09 '20 at 23:20
  • Well do you want to just reference them by indices, or do you want to programmatically locate "each 2x2 matrix containing the same number"? (in any case doing the latter seems like a silly task, the average of a matrix all of whose entries are n, is n) – smci Nov 09 '20 at 23:21
  • The numbers are only meaningful here to illustrate the chunks to which I want to calculate the mean of. My actual matrices are 80x80 where every entry has a different value. – sdaste Nov 09 '20 at 23:28
  • sdaste: Ok, then I would have said *"in 2x2 submatrices, pairing off adjacent rows and columns"* – smci Nov 09 '20 at 23:30

2 Answers2

1

Not sure whether this is what you want

import numpy as np
x = np.arange(1,10).reshape(3,3)
y = np.ones((2,2),dtype=np.int32)
z = np.kron(x,y)
z

enter image description here

def meanpool2d(x):
    h,w = x.shape
    out = np.zeros((h//2,w//2))
    for i in range(h//2):
        for j in range(w//2):
            out[i][j] = np.mean(x[2*i:2*i+2,2*j:2*j+2])
    return out
meanpool2d(z)

enter image description here

TQCH
  • 1,162
  • 1
  • 6
  • 13
1

Construct the input array

import numpy as np
x = np.arange(1,10).reshape(3,3)
x = np.repeat(x, 2, 0)
x = np.repeat(x, 2, 1)
print(x)

Out:

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

Compute the means of all 2x2 blocks

m = (x.reshape(3, 2, -1, 2)
      .swapaxes(1,2)
      .mean((2,3)))
print(m)

Out:

[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32