I am rather new to programming, so I apologise if this is a classic and trivial question. I have a 100x100
2D array of values which is plotted by means of matplotlib
. In this image, each cell has its value (ranging 0.0
to 1.0
) and ID (ranging 0
to 9999
starting from the upper left corner). I want to sample the matrix by using a 2x2 moving window which produces two dictionaries:
- 1st dictionary: the key represents the intersection of 4 cells; the value represents the tuple with the IDs of the 4 neighboring cells (see image below - the intersection is represented by "N");
- 2nd dictionary: the key represents the intersection of 4 cells; the value represents the mean value of the 4 neighboring cells (see image below).
In the example below (upper left panel), where N has ID=0, the 1st dictionary would yield
{'0': (0,1,100,101)}
since the cells are numbered 0 to 99 toward the right hand side and 0 to 9900, step=100, downward. The 2nd dictionary would yield {'0': 0.775}
, as 0.775 is the average value of the 4 neighboring cells of N. Of course, these dictionaries must have as many keys as "intersections" I have on the 2D array.
How can this be accomplished? And are dictionaries the best "tool" in this case? Thank you guys!
PS: I tried my own way but my code is incomplete, wrong, and I cannot get my head around it:
a=... #The 2D array which contains the cell values ranging 0.0 to 1.0
neigh=numpy.zeros(4)
mean_neigh=numpy.zeros(10000/4)
for k in range(len(neigh)):
for i in a.shape[0]:
for j in a.shape[1]:
neigh[k]=a[i][j]
...