W3docs

Peak detection in a 2D array

Here is an example of a Python function that can be used to detect peaks in a 2D array:

Here is an example of a Python function that can be used to detect peaks in a 2D array:

A Python function that can detect peaks in a 2D array

def detect_peaks(arr):
    peaks = []
    for i in range(1, arr.shape[0]-1):
        for j in range(1, arr.shape[1]-1):
            if arr[i,j] > arr[i-1,j] and arr[i,j] > arr[i+1,j] and arr[i,j] > arr[i,j-1] and arr[i,j] > arr[i,j+1]:
                peaks.append((i,j))
    return peaks

This function takes a NumPy 2D array as input and returns a list of peak coordinates in the form of tuples (i, j), where i is the row index and j is the column index. The function checks if the current element is strictly greater than all four of its immediate neighbors (up, down, left, right). If true, the element is considered a peak. Note that boundary elements are intentionally excluded from the check.

You can use this function as follows:

Using the previous Python function to detect peaks in a 2D array

import numpy as np

arr = np.array([
    [1, 2, 3],
    [4, 8, 5],
    [6, 7, 9]
])
print(detect_peaks(arr))

This will print [(1, 1)]

Note that this is a very simple example, and in practice you may need to use more advanced peak detection algorithms depending on the nature of your data. The current implementation uses strict inequality, so elements equal to their neighbors (plateaus) are not detected as peaks.