# How do I get various peak values from a 2-D array or a matrix?

I'm working on 2D array analysis or an image analysis and get to know the different block of peak values marked "circle" in attached plot [e.g. 2*2 matrix] of the 2D array [as shown in Fig. 01].

The image formation of the plot look like as Fig. 02

I visited the link https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710 and use the following script

#NOTE: I get the code from the link above
from scipy import *
from operator import itemgetter
n = 3  # how many fingers are we looking for
#data = [DATA of a 2d array]
width, height = data.shape
# Create an array where every element is a sum of 2x2 squares.
fourSums = data[:-1,:-1] + data[1:,:-1] + data[1:,1:] + data[:-1,1:]

# Find positions of the fingers.
# Pair each sum with its position number (from 0 to width*height-1),
pairs = zip(arange(width*height), fourSums.flatten())
# Sort by descending sum value, filter overlapping squares

def drop_overlapping(pairs):
no_overlaps = []
def does_not_overlap(p1, p2):
i1, i2 = p1[0], p2[0]
r1, col1 = i1 / (width-1), i1 % (width-1)
r2, col2 = i2 / (width-1), i2 % (width-1)
return (max(abs(r1-r2),abs(col1-col2)) >= 2)
for p in pairs:
if all(map(lambda prev: does_not_overlap(p,prev), no_overlaps)):
no_overlaps.append(p)
return no_overlaps

pairs2 = drop_overlapping(sorted(pairs, key=itemgetter(1), reverse=True))

# Take the first n with the heighest values
positions = pairs2[:n]

# Print results print(data, "\n")
for i, val in positions:
row = i // (width-1)
column = i % (width-1)
print("sum = %f @ %d,%d (%d)" % (val, row, column, i))
print(data[row:row+2,column:column+2])


The above script provides 2 adjacent matrix[2*2] of the same peaks.

## 01: Local matrix of the peak
sum = 0.002482 @ 128,190 (65342)
[[0.0006202  0.00062187]
[0.00061926 0.00062093]]
## 02: Local matrix of the peak
sum = 0.002479 @ 128,191 (65343)
[[0.00062187 0.0006184 ]
[0.00062093 0.00061746]]


Also, I've tried with varying 'n' and no. of rows and columns but it gives me different local matrix for the same peak (probably I missed something) which does not match with my expectation. I want to find local peaks or a number of local maxima as shown in fig. 01 and Fig. 02. How can I get the local maxima efficiently? Can anybody help me in this regard?

• Do you mean finding a pair of indices, $n, m$ so that $y[n,m] > y[n\pm1, m\pm1]$? Feb 19, 2022 at 8:47
• Yes, a pair of indices with data (inside the 2 blobs but I got pair of indices inside 1 blob). In Fig. 02, I want to find two local maxima of size [P*Q] from the 2 red blobs encircled. However, I got the 2 maxima of size [2*2] at location (128,190) & (128, 191) that represents 2 maximum data block but located in the same blob.
– CEB
Feb 19, 2022 at 10:12
• Please don’t cross-post. stackoverflow.com/q/71175329/7328782 Feb 19, 2022 at 15:53