python function to find local maxima/peaks from array

1.7k Views Asked by At

i am trying to detect local maxima from a given array. The array is a sinusoidal curve obtained after calculating hough line transform. Here is the imageenter image description here

Here is the numpy file accumulator.npy. Clearly, there are two local maximas. I was wondering what would be the best way to detect those two maxima. Also, how can i plot back lines after finding the maximas ? Thanks.

1

There are 1 best solutions below

2
On

You can use skimage function peak_local_max() to find the peaks. There are more than you seem to be expecting, so I added some Gaussian smoothing for you to experiment with.

There is also some plotting at the end that enables you to visualise the data in 3D better - but you can ignore that.

#!/usr/bin/env python3

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from skimage import img_as_float

# Load data and find maxima
data = np.load('accum.npy')
im = img_as_float(data)
image_max = ndi.maximum_filter(im, size=20, mode='constant')

# Experiment with various smoothing parameters
for sigma in range(4):
    coordinates = peak_local_max(ndi.gaussian_filter(im,sigma=sigma), min_distance=20)
    print(f"Sigma for smoothing: {sigma}, coordinates of peaks:")
    print(coordinates)

# Plotting stuff
sigmaForPlot=0
fig = plt.figure()
ax = plt.axes(projection='3d')
x = np.outer(np.ones(800),np.arange(300))
y = np.outer(np.arange(800), np.ones(300))
ax.plot_surface(x, y,ndi.gaussian_filter(im,sigma=sigmaForPlot),cmap='viridis', edgecolor='none')
ax.set_title('Surface plot')
plt.show()

Sample Output

Sigma for smoothing: 1, coordinates of peaks:
[[595 113]
 [589  36]
 [448  80]
 [400 144]
 [351 260]
 [251 166]
 [210 216]]
Sigma for smoothing: 2, coordinates of peaks:
[[589  36]
 [399 144]
 [239 170]
 [210 216]]
Sigma for smoothing: 3, coordinates of peaks:
[[589  36]
 [398 145]
 [210 216]]

enter image description here