Python library for the detection of peaks and valleys.
- findpeaks.findpeaks.check_logger(verbose: [<class 'str'>, <class 'int'>] = None)
Check the logger.
- findpeaks.findpeaks.convert_verbose_to_new(verbose)
Convert old verbosity to the new.
- findpeaks.findpeaks.convert_verbose_to_old(verbose)
Convert new verbosity to the old ones.
- class findpeaks.findpeaks.findpeaks(method=None, whitelist=['peak', 'valley'], lookahead=200, interpolate=None, limit=None, imsize=None, scale=True, togray=True, denoise='fastnl', window=None, cu=None, params_caerus={}, params={'delta': 0, 'window': 3}, figsize=(15, 8), verbose='info')
Python library for robust detection and analysis of peaks and valleys in 1D and 2D data.
findpeaks is a comprehensive library for detecting, analyzing, and visualizing peaks and valleys in both 1D vectors and 2D arrays (images). It provides multiple detection methods including topology-based persistent homology, traditional peak detection algorithms, and mask-based approaches.
Key Features: - Multiple Detection Methods: Topology (persistent homology), peakdetect, caerus, and mask-based detection - 1D and 2D Support: Works with time series, signals, images, and spatial data - Advanced Preprocessing: Denoising, scaling, interpolation, and image preprocessing - Rich Visualization: Persistence diagrams, 3D mesh plots, preprocessing steps, and masking plots - Robust Analysis: Mathematically stable methods with quantitative significance measures
Detection Methods: - Topology: Uses persistent homology for robust peak detection with mathematical stability - Peakdetect: Traditional algorithm for 1D peak detection with lookahead and delta parameters - Caerus: Advanced peak detection with multiple optimization strategies - Mask: Local maximum filtering for 2D peak detection
Applications: - Signal processing and time series analysis - Image processing and feature detection - Hough Transform applications with enhanced robustness - Scientific data analysis and visualization - Peak finding in noisy or complex datasets
Examples
>>> from findpeaks import findpeaks >>> >>> # 1D vector example >>> X = [9,60,377,985,1153,672,501,1068,1110,574,135,23,3,47,252,812,1182,741,263,33] >>> fp = findpeaks(method='peakdetect', lookahead=1, interpolate=10) >>> results = fp.fit(X) >>> fp.plot() >>> >>> # 2D array example >>> X = fp.import_example('2dpeaks') >>> results = fp.fit(X) >>> fp.plot() >>> >>> # Image processing example >>> fp = findpeaks(method='topology', imsize=(300,300), denoise='fastnl', params={'window': 30}) >>> X = fp.import_example('2dpeaks_image') >>> results = fp.fit(X) >>> fp.plot() >>> >>> # Advanced visualization >>> fp.plot_preprocessing() # Show preprocessing steps >>> fp.plot_persistence() # Show persistence diagram >>> fp.plot_mesh() # Show 3D mesh plot
References
Johannes Ferner et al, Persistence-based Hough Transform for Line Detection, https://arxiv.org/abs/2504.16114
- check_logger(verbose: [<class 'str'>, <class 'int'>] = None)
Check the logger.
- fit(X, x=None)
Detect peaks and valleys in 1D vector or 2D-array data.
Description
Performs peak and valley detection on the input data using the configured method. Automatically determines whether the input is 1D or 2D and applies appropriate preprocessing and detection algorithms.
- param X:
Input data for peak detection. Can be: - 1D array/list: Time series, signal data, or vector data - 2D array: Image data, spatial data, or matrix data - pandas DataFrame: Will be converted to numpy array
- type X:
array-like
- param x:
X-coordinates for 1D data. If None, uses sequential indices [0, 1, 2, …]. Only used for 1D data visualization and result mapping.
- type x:
array-like, optional (default: None)
- returns:
Dictionary containing detection results with the following keys:
For 1D data: - ‘df’: pandas DataFrame with original data coordinates and detection results - ‘df_interp’: pandas DataFrame with interpolated data (if interpolation used) - ‘persistence’: pandas DataFrame with persistence scores (topology method only) - ‘Xdetect’: numpy array with detection scores - ‘Xranked’: numpy array with ranked peak/valley indices
For 2D data: - ‘Xraw’: numpy array of original input data - ‘Xproc’: numpy array of preprocessed data - ‘Xdetect’: numpy array with detection scores (same shape as input) - ‘Xranked’: numpy array with ranked peak/valley indices (same shape as input) - ‘persistence’: pandas DataFrame with persistence scores (topology method only) - ‘groups0’: list of homology groups (topology method only)
DataFrame columns (when applicable): - ‘x’, ‘y’: Coordinates of detected features - ‘peak’: Boolean indicating if point is a peak - ‘valley’: Boolean indicating if point is a valley - ‘score’: Persistence or detection score - ‘rank’: Ranking of feature significance (1 = most significant) - ‘labx’: Label/group assignment for connected components
- rtype:
dict
Examples
>>> from findpeaks import findpeaks >>> >>> # 1D peak detection >>> X = [1, 2, 5, 3, 2, 1, 4, 6, 4, 2, 1] >>> fp = findpeaks(method='peakdetect', lookahead=1) >>> results = fp.fit(X) >>> print(f"Found {results['df']['peak'].sum()} peaks") >>> >>> # 2D peak detection >>> X = fp.import_example('2dpeaks') >>> fp = findpeaks(method='topology', limit=0.1) >>> results = fp.fit(X) >>> print(f"Found {len(results['persistence'])} significant features")
Notes
The method automatically handles data type conversion and preprocessing
Results are stored in the object for subsequent plotting and analysis
For topology method, persistence scores provide quantitative significance measures
Interpolation (if enabled) creates smoother data for better detection
- import_example(data='2dpeaks', url=None, sep=';', datadir=None)
Import example dataset from github source.
Dataset Import Descriptions
Import one of the few datasets from github source or specify your own download url link.
- param data:
Name of datasets: “1dpeaks”, “2dpeaks”, “2dpeaks_image”, ‘2dpeaks_image_2’, ‘btc’, ‘facebook’
- type data:
str
- param url:
url link to to dataset.
- type url:
str
- param datadir:
Directory to store downloaded datasets in. Defaults to data sub-directory of findpeaks install location.
- type datadir:
path-like
- returns:
Dataset containing mixed features.
- rtype:
pd.DataFrame()
- imread(path)
Read file from disk or url.
- Parameters:
path (String) – filepath or Url.
- Returns:
X
- Return type:
Numpy array
- peaks1d(X, x=None, method='peakdetect', height=0)
Detect peaks and valleys in 1D array data.
Method Description
Performs peak and valley detection on 1D data using the specified method. Supports multiple detection algorithms with different characteristics:
topology: Persistent homology-based detection (most robust, handles noise well)
peakdetect: Traditional algorithm with lookahead and delta parameters
caerus: Advanced peak detection with optimization strategies
- param X:
1D input data (vector, time series, or signal data)
- type X:
array-like
- param x:
X-coordinates for the data points. If None, uses sequential indices.
- type x:
array-like, optional (default: None)
- param method:
Detection method to use: - ‘topology’: Persistent homology-based detection - ‘peakdetect’: Traditional peak detection algorithm - ‘caerus’: Advanced peak detection with optimization
- type method:
str, optional (default: ‘peakdetect’)
- param height:
Minimum height requirement for peaks (peakdetect method only)
- type height:
float, optional (default: 0)
- returns:
Dictionary containing detection results:
Common keys: - ‘df’: pandas DataFrame with original data and detection results - ‘df_interp’: pandas DataFrame with interpolated data (if interpolation used)
For topology method: - ‘persistence’: pandas DataFrame with persistence scores and coordinates - ‘Xdetect’: numpy array with detection scores - ‘Xranked’: numpy array with ranked peak/valley indices - ‘groups0’: list of homology groups
For peakdetect method: - ‘peakdetect’: dict with peak detection results
For caerus method: - ‘caerus’: dict with caerus detection results - ‘model’: caerus model object
DataFrame columns: - ‘x’, ‘y’: Coordinates and values - ‘peak’: Boolean indicating peak locations - ‘valley’: Boolean indicating valley locations - ‘score’: Detection or persistence scores - ‘rank’: Feature ranking (1 = most significant) - ‘labx’: Component labels
- rtype:
dict
Examples
>>> from findpeaks import findpeaks >>> >>> # Basic peak detection >>> X = [1, 2, 5, 3, 2, 1, 4, 6, 4, 2, 1] >>> fp = findpeaks(method='peakdetect', lookahead=1) >>> results = fp.peaks1d(X) >>> >>> # Topology-based detection with persistence >>> fp = findpeaks(method='topology', limit=0.1) >>> results = fp.peaks1d(X) >>> print(f"Persistence scores: {results['persistence']['score'].values}")
Notes
The topology method provides the most robust detection with mathematical stability
Interpolation (if enabled) creates smoother data for better detection
Persistence scores quantify the significance of detected features
Results are automatically stored in the object for plotting and analysis
- peaks2d(X, method='topology')
Detect peaks and valleys in 2D-array or image data.
Detection Description
Performs peak and valley detection on 2D data (images, spatial data, or matrices). Applies preprocessing steps including denoising, scaling, and grayscale conversion before detection. Supports multiple detection algorithms optimized for 2D data.
Preprocessing Pipeline: 1. Resizing (optional): Reduce image size for faster computation 2. Scaling (optional): Normalize values to [0-255] range 3. Grayscale conversion (optional): Convert color images to grayscale 4. Denoising (optional): Apply noise reduction filters
Detection Methods: - topology: Persistent homology-based detection (most robust, handles noise well) - mask: Local maximum filtering for peak detection
- param X:
2D input data (image, spatial data, or matrix)
- type X:
array-like
- param method:
Detection method to use: - ‘topology’: Persistent homology-based detection (recommended) - ‘mask’: Local maximum filtering
- type method:
str, optional (default: ‘topology’)
- returns:
Dictionary containing detection results:
Common keys: - ‘Xraw’: numpy array of original input data - ‘Xproc’: numpy array of preprocessed data - ‘Xdetect’: numpy array with detection scores (same shape as input) - ‘Xranked’: numpy array with ranked peak/valley indices (same shape as input)
For topology method: - ‘persistence’: pandas DataFrame with persistence scores and coordinates - ‘groups0’: list of homology groups
Persistence DataFrame columns: - ‘x’, ‘y’: Coordinates of detected features - ‘birth_level’: Birth level in persistence diagram - ‘death_level’: Death level in persistence diagram - ‘score’: Persistence scores (higher = more significant) - ‘peak’: Boolean indicating peak locations - ‘valley’: Boolean indicating valley locations
- rtype:
dict
Examples
>>> from findpeaks import findpeaks >>> >>> # Basic 2D peak detection >>> X = fp.import_example('2dpeaks') >>> fp = findpeaks(method='topology', limit=0.1) >>> results = fp.peaks2d(X) >>> >>> # With preprocessing >>> fp = findpeaks(method='topology', imsize=(300,300), denoise='fastnl') >>> results = fp.peaks2d(X) >>> print(f"Found {len(results['persistence'])} significant features")
Notes
The topology method provides the most robust detection with mathematical stability
Preprocessing steps can significantly improve detection quality on noisy data
Persistence scores quantify the significance of detected features
Results are automatically stored in the object for plotting and analysis
Color images are automatically converted to grayscale for topology method
See also
fit
Main detection method for both 1D and 2D data
peaks1d
1D peak detection method
preprocessing
Detailed preprocessing pipeline
plot
Visualize detection results
- plot(limit=None, legend=True, figsize=None, cmap=None, text=True, s=None, marker='x', color='#FF0000', xlabel='x-axis', ylabel='y-axis', figure_order='vertical', fontsize=18)
Plot peak detection results.
Plot Description
Creates visualizations of peak detection results. Automatically determines the appropriate plot type based on the data dimensionality (1D or 2D).
For 1D data: Creates line plots with peak/valley markers For 2D data: Creates image plots with peak/valley annotations
- param limit:
Persistence threshold for filtering results. Only features with persistence > limit are displayed (topology method only).
- type limit:
float, optional (default: None)
- param legend:
Whether to display the plot legend.
- type legend:
bool, optional (default: True)
- param figsize:
Figure size as (width, height) in inches. If None, uses default size.
- type figsize:
tuple, optional (default: None)
- param cmap:
Colormap for 2D plots. If None, automatically chooses based on data type. Common options: ‘gray’, ‘hot’, ‘viridis’, plt.cm.hot_r
- type cmap:
str or matplotlib.colors.Colormap, optional (default: None)
- param text:
Whether to display peak/valley labels on 2D plots.
- type text:
bool, optional (default: True)
- param s:
Marker size for peak/valley indicators. If None, automatically sizes based on peak significance.
- type s:
float, optional (default: None)
- param marker:
Marker style for peaks. Common options: ‘x’, ‘o’, ‘+’, ‘*’
- type marker:
str, optional (default: ‘x’)
- param color:
Color for peak/valley markers (hex color code).
- type color:
str, optional (default: ‘#FF0000’)
- param xlabel:
Label for the x-axis.
- type xlabel:
str, optional (default: ‘x-axis’)
- param ylabel:
Label for the y-axis.
- type ylabel:
str, optional (default: ‘y-axis’)
- param figure_order:
Layout direction for subplots: ‘vertical’ or ‘horizontal’.
- type figure_order:
str, optional (default: ‘vertical’)
- param fontsize:
Font size for text labels and axis labels.
- type fontsize:
int, optional (default: 18)
- returns:
For 1D data: (ax1, ax2) - matplotlib axes objects For 2D data: (ax1, ax2, ax3) - matplotlib axes objects Returns None if no results are available to plot
- rtype:
tuple or None
Examples
>>> from findpeaks import findpeaks >>> >>> # Basic plotting >>> fp = findpeaks(method='topology') >>> results = fp.fit(X) >>> fp.plot() >>> >>> # Customized plotting >>> fp.plot(limit=0.1, marker='o', color='blue', fontsize=14)
Notes
Must call fit() before plotting
For 1D data, shows both original and interpolated results (if applicable)
For 2D data, shows input, processed, and detection results
Peak/valley markers are automatically sized based on significance
Use limit parameter to filter out low-significance features
See also
plot1d
1D-specific plotting
plot_mask
2D-specific plotting with masking
plot_persistence
Persistence diagram visualization
plot_mesh
3D mesh visualization
- plot1d(legend=True, figsize=None, xlabel='x-axis', ylabel='y-axis', fontsize=18, params_line={'color': None, 'linewidth': 2}, params_peak_marker={'color': 'red', 'edgecolors': 'red', 'linewidths': 3, 'marker': 'x', 's': 120}, params_valley_marker={'color': 'blue', 'edgecolors': 'lightblue', 'linewidths': 3, 'marker': 'o', 's': 120})
Plot the 1D results.
- Parameters:
legend (bool, (default: True)) – Show the legend.
figsize ((int, int), (default: None)) – (width, height) in inches.
fontsize (int (default: 10)) – Font size for the text labels on the plot.
params_line (dict (default: {'color':None, 'linewidth':2})) – Parameters for the line plot.
params_peak_marker (dict (default: None)) – Parameters for the peak markers.
params_valley_marker (dict (default: None)) – Parameters for the valley markers.
- Returns:
fig_axis
- Return type:
tuple containing axis for each figure.
- plot2d(figsize=None, limit=None, figure_order='vertical', fontsize=18)
Plot the 2d results.
- Parameters:
figsize ((int, int), (default: None)) – (width, height) in inches.
- Returns:
fig_axis
- Return type:
tuple containing axis for each figure.
- plot_mask(limit=None, figsize=None, cmap=None, text=True, s=None, marker='x', color='#FF0000', figure_order='vertical', fontsize=18)
Plot the masking.
- Parameters:
limit (float, (default : None)) – Values > limit are set as regions of interest (ROI).
figsize ((int, int), (default: None)) – (width, height) in inches.
cmap (object (default : None)) – Colormap. The default is derived wether image is convert to grey or not. Other options are: plt.cm.hot_r.
text (Bool (default : True)) – Include text to the 2D-image that shows the peaks (p-number) and valleys (v-number)
s (size (default: None)) – Size of the marker.
marker (str (default: 'x')) – Marker type.
color (str (default: '#FF0000')) – Hex color of the marker.
figure_order (str (default: 'vertical')) – Order of the subplots (‘vertical’ or ‘horizontal’).
fontsize (int (default: 10)) – Font size for the text labels on the plot.
- Returns:
fig_axis
- Return type:
tuple containing axis for each figure.
- plot_mesh(wireframe=True, surface=True, rstride=2, cstride=2, cmap=<matplotlib.colors.LinearSegmentedColormap object>, view=None, xlim=None, ylim=None, zlim=None, title='', figsize=None, savepath=None)
Plot the 3D-mesh.
- Parameters:
wireframe (bool, (default is True)) – Plot the wireframe
surface (bool, (default is True)) – Plot the surface
rstride (int, (default is 2)) – Array row stride (step size).
cstride (int, (default is 2)) – Array column stride (step size).
figsize ((int, int), (default: None)) – (width, height) in inches.
view (tuple, (default : None)) –
Rotate the mesh plot.
(0, 0) : y vs z
(0, 90) : x vs z
(90, 0) : y vs x
(90, 90) : x vs y
cmap (object) – Colormap. The default is plt.cm.hot_r.
xlim (tuple(int, int), (default: None)) – x-limit in the axis. None: No limit. [1, 5]: Limit between the range 1 and 5. [1, None]: Limit between range 1 and unlimited. [None, 5]: Limit between range unlimited and 5.
ylim (tuple(int, int), (default: None)) – y-limit in the axis. None: No limit. [1, 5]: Limit between the range 1 and 5. [1, None]: Limit between range 1 and unlimited. [None, 5]: Limit between range unlimited and 5.
zlim (tuple(int, int), (default: None)) – z-limit in the axis. None: No limit. [1, 5]: Limit between the range 1 and 5. [1, None]: Limit between range 1 and unlimited. [None, 5]: Limit between range unlimited and 5.
figsize – (width, height) in inches.
savepath (bool (default : None)) – Path with filename to save the figure, eg: ‘./tmp/my_image.png’
Example
>>> # Import library >>> from findpeaks import findpeaks >>> # >>> # Initialize >>> fp = findpeaks(method='topology',imsize=False,scale=False,togray=False,denoise=None,params={'window': 15}) >>> # >>> # Load example data set >>> X = fp.import_example('2dpeaks') >>> # >>> # Fit model >>> fp.fit(X) >>> # >>> # Create mesh plot >>> fp.plot_mesh() >>> # Create mesh plot with limit on x-axis and y-axis >>> fp.plot_mesh(xlim=[10, 30], ylim=[4, 10], zlim=[None, 8])
- Returns:
fig_axis
- Return type:
tuple containing axis for each figure.
- plot_persistence(figsize=(20, 8), fontsize_ax1=14, fontsize_ax2=14, xlabel='x-axis', ylabel='y-axis', s=20, marker='x', color='#FF0000')
Plot the homology-peristence.
- Parameters:
figsize ((int, int), (default: None)) – (width, height) in inches.
fontsize_ax1 (int, (default: 14)) – Font size for the labels in the left figure. Choose None for no text-labels.
fontsize_ax2 (int, (default: 14)) – Font size for the labels in the right figure. Choose None for no text-labels.
- Returns:
ax1 (object) – Figure axis 1.
ax2 (object) – Figure axis 2.
- plot_preprocessing()
Plot the pre-processing steps.
- Return type:
None.
- preprocessing(X, showfig=False)
Apply preprocessing pipeline to 2D array (image) data.
Preprocessing Description
Performs a series of optional preprocessing steps to prepare 2D data for peak detection. The preprocessing pipeline can significantly improve detection quality, especially for noisy or complex images.
Preprocessing Steps (in order): 1. Resizing: Reduce image dimensions for faster computation 2. Scaling: Normalize pixel values to [0-255] range for consistent processing 3. Grayscale conversion: Convert color images to grayscale (required for topology method) 4. Denoising: Apply noise reduction filters to improve detection quality
- param X:
Input 2D data (image, spatial data, or matrix)
- type X:
numpy.ndarray
- param showfig:
If True, displays intermediate preprocessing steps as subplots. Useful for understanding how each step affects the data.
- type showfig:
bool, optional (default: False)
- returns:
Preprocessed 2D array ready for peak detection
- rtype:
numpy.ndarray
Examples
>>> from findpeaks import findpeaks >>> >>> # Basic preprocessing >>> fp = findpeaks(scale=True, togray=True, denoise='fastnl') >>> X_processed = fp.preprocessing(X) >>> >>> # With visualization >>> fp.preprocessing(X, showfig=True)
Notes
Preprocessing steps are applied in the order listed above
Each step is optional and controlled by initialization parameters
Grayscale conversion is required for topology method
Denoising can significantly improve detection on noisy data
Resizing reduces computation time but may lose fine details
See also
peaks2d
2D peak detection with automatic preprocessing
plot_preprocessing
Visualize preprocessing steps
- findpeaks.findpeaks.get_logger()
- findpeaks.findpeaks.import_example(data='2dpeaks', url=None, sep=';', datadir=None)
Import example dataset from github source.
Dataset Import Description
Import one of the few datasets from github source or specify your own download url link.
- param data:
Name of datasets: “2dpeaks” or “2dpeaks_image” or ‘2dpeaks_image_2’
- type data:
str
- param url:
url link to to dataset.
- type url:
str
- param datadir:
Directory to store downloaded datasets in. Defaults to data sub-directory of findpeaks install location.
- type datadir:
path-like
- returns:
Dataset containing mixed features.
- rtype:
pd.DataFrame()
- findpeaks.findpeaks.is_url(url)
- findpeaks.findpeaks.set_logger(verbose: [<class 'str'>, <class 'int'>] = 'info', return_status: bool = False)
Set the logger for verbosity messages.
- Parameters:
verbose (str or int, optional, default='info' (20)) – Logging verbosity level. Possible values: - 0, 60, None, ‘silent’, ‘off’, ‘no’ : no messages. - 10, ‘debug’ : debug level and above. - 20, ‘info’ : info level and above. - 30, ‘warning’ : warning level and above. - 50, ‘critical’ : critical level and above.
- Returns:
None.
> # Set the logger to warning
> set_logger(verbose=’warning’)
> # Test with different messages
> logger.debug(“Hello debug”)
> logger.info(“Hello info”)
> logger.warning(“Hello warning”)
> logger.critical(“Hello critical”)
- findpeaks.stats.denoise(X, method='fastnl', window=9, cu=0.25)
Denoise input data.
Denoising Description
Denoising the data is very usefull before detection of peaks. Multiple methods are implemented to denoise the data. The bilateral filter uses a Gaussian filter in the space domain, but it also uses one more (multiplicative) Gaussian filter component which is a function of pixel intensity differences. The Gaussian function of space makes sure that only pixels are ‘spatial neighbors’ are considered for filtering, while the Gaussian component applied in the intensity domain (a Gaussian function of intensity differences) ensures that only those pixels with intensities similar to that of the central pixel (‘intensity neighbors’) are included to compute the blurred intensity value. As a result, this method preserves edges, since for pixels lying near edges, neighboring pixels placed on the other side of the edge, and therefore exhibiting large intensity variations when compared to the central pixel, will not be included for blurring.
- param X:
Input image data.
- type X:
array-like
- param method:
- Filtering method to remove noise
None
‘fastnl’
‘bilateral’
‘lee’
‘lee_enhanced’
‘lee_sigma’
‘kuan’
‘frost’
‘median’
‘mean’
- type method:
string, (default: ‘fastnl’, None to disable)
- param window:
Denoising window. Increasing the window size may removes noise better but may also removes details of image in certain denoising methods.
- type window:
int, (default: 3)
- param cu:
The noise variation coefficient, applies for methods: [‘kuan’,’lee’,’lee_enhanced’]
- type cu:
float, (default: 0.25)
- param sigma:
Speckle noise standard deviation, applies for methods: [‘lee_sigma’]
- type sigma:
float, (default: 0.9)
- param num_looks:
Number of looks of the SAR img, applies for methods: [‘lee_sigma’]
- type num_looks:
int, (default: 1)
- param tk:
Threshold of neighbouring pixels outside of the 98th percentile, applies for methods: [‘lee_sigma’]
- type tk:
int, (default: 5)
- returns:
X – Denoised data.
- rtype:
array-like
References
- findpeaks.stats.disable_tqdm()
Set the logger for verbosity messages.
- findpeaks.stats.generate_default_neighborhood(p, h, w, eight_neighborship=True)
- findpeaks.stats.mask(X, limit=0)
Determine peaks in 2d-array using a mask.
Mask Method Description
Takes an image and detect the peaks using the local maximum filter. Returns a boolean mask of the peaks (i.e. 1 when the pixel’s value is the neighborhood maximum, 0 otherwise)
- param X:
Input image data.
- type X:
array-like
- param limit:
Values > limit are set as regions of interest (ROI).
- type limit:
float, (default: None)
- returns:
- Xraw: array-like.
Input image.
- Xdetect: array-like (same shape as input data)
detected peaks with respect the input image. Elements are the scores.
- Xranked: array-like (same shape as input data)
detected peaks with respect the input image. Elements are the ranked peaks (1=best).
- rtype:
dict()
References
- findpeaks.stats.normalize(X, minscale=0.5, maxscale=4, scaler: str = 'zscore')
- findpeaks.stats.resize(X, size=None)
Resize image.
- Parameters:
X (array-like) – Input image data.
size (tuple, (default: None)) – size to desired (width,length).
- Returns:
X
- Return type:
array-like
- findpeaks.stats.reverse_values(image_array)
- findpeaks.stats.scale(X)
Normalize data (image) by scaling.
Scaling Description
Scaling in range [0-255] by img*(255/max(img))
- param X:
Input image data.
- type X:
array-like
- returns:
X – Scaled image.
- rtype:
array-like
- findpeaks.stats.togray(X)
Convert color to grey-image.
Grayscale Conversion Description
Convert 3d-RGB colors to 2d-grey image.
- param X:
Input image data.
- type X:
array-like
- returns:
X – 2d-image.
- rtype:
array-like
- findpeaks.stats.topology(X, limit=None, reverse=True, neighborhood_generator=None)
Determine peaks using topology method based on persistent homology.
Topology Method Description
The topology method uses persistent homology to detect peaks and valleys in data. The core idea is to consider the function graph that assigns each pixel its level, then simulate a water level that continuously descends to lower levels.
At local maxima, islands emerge (birth events). At saddle points, two islands merge; the lower island merges into the higher island (death events). The persistence diagram depicts death-over-birth values of all islands, where persistence is the difference between birth and death levels - the vertical distance from the main diagonal.
Advantages over thresholding methods:
Naturally handles noise and artifacts that affect simple thresholding
Provides quantitative significance measures (persistence scores)
Mathematically stable and robust
Enables principled filtering based on persistence rather than arbitrary thresholds
Applications:
Line Detection: Particularly effective for Hough Transform applications where traditional voting methods are susceptible to noise. The persistence-based approach significantly outperforms threshold-based methods in synthetic data experiments.
Peak Detection: General peak/valley detection in 1D and 2D data
Feature Detection: Robust detection of significant features in noisy data
Hough Transform Integration:
This method addresses key limitations of classical Hough transform voting:
Replaces simple thresholding with persistent homology-based peak detection
Enhances robustness against noise and artifacts
Provides mathematical stability guarantees
Enables principled parameter selection based on persistence scores
The method not only identifies local maxima but also quantifies their significance through persistence scores, allowing for principled filtering of peaks based on their topological importance rather than arbitrary thresholds.
- param X:
Input data.
- type X:
array-like data
- param limit:
score > limit are set as regions of interest (ROI). None: Take all positions into consideration.
- type limit:
float, (default: None)
- param reverse:
For 1d-vectors, reverse should be True to detect peaks and valleys. For 2d-images, the peaks are detected by setting reverse=True and valleys by reverse=False.
- type reverse:
bool, (default: True)
- param neighborhood_generator:
Custom neighborhood generator function. If None, uses default 8-neighborhood. The function should take parameters (p, w, h) and return neighboring coordinates.
- type neighborhood_generator:
callable, (default: None)
- returns:
- Xdetect: array-like
detected peaks in the same shape as the input image. Elements are the scores (higher is better).
- Xranked: array-like
detected peaks in the same shape as the input image. Elements are the ranked peaks (1=best).
- peak: array-like
Detected peaks
- valley: array-like
Detected valley
- groups0: array-like
Unstructured results
- persistence: DataFrame()
DataFrame with columns:
x, y: Coordinates
birth: Birth level, tuple(coordinate, rgb value)
death: Death level, tuple(coordinate, rgb value)
score: Persistence scores
- rtype:
dict()
References
Johannes Ferner et al, Persistence-based Hough Transform for Line Detection, https://arxiv.org/abs/2504.16114
Edelsbrunner and J. Harer, Computational Topology. An Introduction, 2010, ISBN 0-8218-4925-5.
Initial implementation: Stefan Huber <shuber@sthu.org>, editted by: Erdogan Taskesen <erdogant@gmail.com>, 2020
- findpeaks.stats.topology2d(X, limit=None, whitelist=['peak', 'valley'])
Determine peaks and valleys in 2d-array using toplogy method.
Topology 2D Description
This function calls the topology function that ONLY computes peaks in case of 2d-arrays. To detect the valleys, the image is inverted and the topology function is called. The final results is the combined peak and valleys.
- param X:
Input data.
- type X:
array-like data
- param limit:
score > limit are set as regions of interest (ROI).
- type limit:
float, (default: None)
- returns:
- Xdetect: array-like
detected peaks/valleys in the same shape as the input image. Elements are the scores. (high=best peak and low=best valley).
- Xranked: array-like
detected peaks/valleys in the same shape as the input image. Elements are the ranked peaks (1=best peak and -1 is best valley).
- persistence: DataFrame().
x, y: Coordinates
birth: Birth level, tuple(coordinate, rgb value)
death: Death level, tuple(coordinate, rgb value)
score: Persistence scores
peak: True if peak
valley: True if valley
- rtype:
dict()
- findpeaks.interpolate.interpolate_line1d(X, n=3, method=2, showfig=False)
Interpolate 1d-vector.
- Parameters:
X (array-like (1D-vector)) – Input image data.
n (int, (default : 3)) – The interpolation factor. The data is interpolation by a factor n.
method (str (default: 'linear')) –
- String or integer
0 : order degree
1 : order degree
2 : order degree
3 : order degree
’linear’ (default)
’nearest’
’zero’
’slinear’
’quadratic’
’cubic’
’previous’
’next’
- showfigbool, (defaultFalse)
Show the figure.
- Returns:
X – Interpolated data.
- Return type:
array-like (1D-vector)
- findpeaks.interpolate.interpolate_line2d(xs, ys=None, interpol=3, window=3)
interpolate 2D vector.
2D Interpolation Description
Smoothing a 2d vector can be challanging if the data is low sampled. This function contains two steps. First interpolation of the input line followed by a convolution.
- param xs:
Data points for the x-axis.
- type xs:
array-like
- param ys:
Data points for the y-axis.
- type ys:
array-like
- param interpol:
The interpolation factor. The data is interpolation by a factor n before the smoothing step.
- type interpol:
int, (default : 3)
- param window:
Smoothing window that is used to create the convolution and gradually smoothen the line.
- type window:
int, (default : 3)
- returns:
xnew (array-like) – Data points for the x-axis.
ynew (array-like) – Data points for the y-axis.
- findpeaks.interpolate.interpolate_nans(X, method='linear', replace_value_to_nan=None)
Interpolate the nan values in an 1D array.
- Parameters:
X (array-like) – input data X.
replace_value_to_nan (float (default: None)) – Replace value to np.nan. * None : take finite data: interplate np.nan. * 0 : take np.nan with the additional value (alternative)
method (str (default: 'linear')) – String or integer * 0 : order degree * 1 : order degree * 2 : order degree * 3 : order degree * ‘linear’ (default) * ‘nearest’ * ‘zero’ * ‘slinear’ * ‘quadratic’ * ‘cubic’ * ‘previous’ * ‘next’
- Return type:
None.
Examples
>>> X = np.array([1,2,3,np.nan,np.nan,6,7,np.nan,9,10]) >>> Xint1 = interpolate_nans(X) >>> Xint2 = interpolate_nans(X, method=0)
- findpeaks.interpolate.plot(X, bootstdata, method)
- findpeaks.filters.frost.calculate_all_Mi(window_flat, factor_A, window)
Compute all the weights of pixels in the window.
- findpeaks.filters.frost.calculate_local_weight_matrix(window, factor_A)
Returns an array with the weights for the pixels in the given window.
- findpeaks.filters.frost.compute_coef_var(image, x_start, x_end, y_start, y_end)
Compute coefficient of variation in a window of [x_start: x_end] and [y_start:y_end] within the image.
- findpeaks.filters.frost.frost_filter(img, damping_factor=2.0, win_size=3)
Frost filter.
Frost Filter Description
Apply frost filter to a numpy matrix containing the image, with a window of win_size x win_size. By default, the window size is 3x3.
- param img:
Input image.
- type img:
array-like
- param damping_factor:
Damping factor.
- type damping_factor:
float (default: 2.0)
- param win_size:
Window size.
- type win_size:
int, int (default: 3)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # frost filter >>> img_filtered = findpeaks.stats.frost_filter(img.copy(), damping_factor=2, win_size=15) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Frost filter')
- findpeaks.filters.lee.lee_filter(img, win_size=3, cu=0.25)
Lee filter.
Lee Filter Description
The Additive Noise Lee Despeckling Filter. Apply lee to a numpy matrix containing the image, with a window of win_size x win_size. Let’s assume that the despeckling noise is additive with a constant mean of zero, a constant variance, and drawn from a Gaussian distribution. Use a window (I x J pixels) to scan the image with a stride of 1 pixels (and I will use reflective boundary conditions). The despeckled value of the pixel in the center of the window located in the ith row and jth column is, zhat_ij = mu_k + W*(z_ij = mu_z), where mu_k is the mean value of all pixels in the window centered on pixel i,j, z_ij is the unfiltered value of the pixel, and W is a weight calculated as, W = var_k / (var_k + var_noise), where var_k is the variance of all pixels in the window and var_noise is the variance of the speckle noise. A possible alternative to using the actual value of the center pixel for z_ij is to use the median pixel value in the window. The parameters of the filter are the window/kernel size and the variance of the noise (which is unknown but can perhaps be estimated from the image as the variance over a uniform feature smooth like the surface of still water). Using a larger window size and noise variance will increase radiometric resolution at the expense of spatial resolution. For more info on the Lee Filter and other despeckling filters see http://desktop.arcgis.com/en/arcmap/10.3/manage-data/raster-and-images/speckle-function.htm Assumes noise mean = 0 If you don’t want the window to be a square of size x size, just replace uniform_filter with something else (convolution with a disk, gaussian filter, etc). Any type of (weighted) averaging filter will do, as long as it is the same for calculating both img_mean and img_square_mean. The Lee filter seems rather old-fashioned as a filter. It won’t behave well at edges because for any window that has an edge in it, the variance is going to be much higher than the overall image variance, and therefore the weights (of the unfiltered image relative to the filtered image) are going to be close to 1.
- param img:
Input image.
- type img:
array-like
- param win_size:
Window size.
- type win_size:
int, int (default: 3)
- param cu:
cu factor.
- type cu:
float (default: 0.25)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # Filter >>> img_filtered = findpeaks.stats.lee_filter(img.copy(), win_size=15, cu=0.25) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Lee filter')
- findpeaks.filters.kuan.kuan_filter(img, win_size=3, cu=0.25)
Kuan filter.
Kuan Filter Description
Apply kuan to a numpy matrix containing the image, with a window of win_size x win_size.
- param img:
Input image.
- type img:
array-like
- param win_size:
Window size.
- type win_size:
int, int (default: 3)
- param cu:
cu factor.
- type cu:
float (default: 0.25)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # Filter >>> img_filtered = findpeaks.stats.kuan_filter(img.copy(), win_size=15, cu=0.25) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Kuan filter')
- findpeaks.filters.kuan.weighting(window, cu=0.25)
Computes the weighthing function for Kuan filter using cu as the noise coefficient.
- findpeaks.filters.lee_enhanced.assert_parameters(win_size, k, cu, cmax)
Asserts parameters in range.
- Parameters:
win_size (int) – Window size parameter.
k (float) – k parameter in range [0:10].
cu (float) – cu parameter, must be positive.
cmax (float) – cmax parameter, must be positive and greater equal than cu.
- findpeaks.filters.lee_enhanced.lee_enhanced_filter(img, win_size=3, k=1.0, cu=0.523, cmax=1.73)
Lee enhanced filter.
Enhanced Lee Filter Description
Apply Enhanced Lee filter to a numpy matrix containing the image, with a window of win_size x win_size.
- param img:
Input image.
- type img:
array-like
- param win_size:
Window size.
- type win_size:
int, int (default: 3)
- param cu:
cu factor.
- type cu:
float (default: 0.25)
- param k:
Kvalue.
- type k:
float, (default: 1.0)
- param cmax:
cmax value.
- type cmax:
float, (default: 1.73)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # Filter >>> img_filtered = findpeaks.stats.lee_enhanced_filter(img.copy(), win_size=15) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Lee enhanced filter')
- findpeaks.filters.lee_enhanced.weighting(pix_value, window, k=1.0, cu=0.523, cmax=1.73)
Computes the weighthing function for Lee filter using cu as the noise coefficient.
- findpeaks.filters.mean.assert_indices_in_range(width, height, xleft, xright, yup, ydown)
Asserts index out of image range.
- findpeaks.filters.mean.mean_filter(img, win_size=3)
Mean filter.
Mean Filter Description
Apply a ‘mean filter’ to ‘img’ with a window size equal to ‘win_size’.
- param img:
Input image.
- type img:
array-like
- param win_size:
The size of the windows.
- type win_size:
int, int (default: 3)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # Filter >>> img_filtered = findpeaks.stats.mean_filter(img.copy(), win_size=15) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Mean filter')
- findpeaks.filters.median.median_filter(img, win_size=3)
Median Filter.
Median Filter Description
Apply a ‘median filter’ to ‘img’ with a window size equal to ‘win_size’.
- param img:
Input image.
- type img:
array-like
- param win_size:
The size of the windows.
- type win_size:
int, int (default: 3)
- returns:
img_filtered – Filtered image.
- rtype:
array-like
Examples
>>> import findpeaks >>> import matplotlib.pyplot as plt >>> img = findpeaks.import_example('2dpeaks_image') >>> # Resize >>> img = findpeaks.stats.resize(img, size=(300,300)) >>> # Make grey image >>> img = findpeaks.stats.togray(img) >>> # Scale between [0-255] >>> img = findpeaks.stats.scale(img) >>> # Filter >>> img_filtered = findpeaks.stats.median_filter(img.copy(), win_size=15) >>> >>> plt.figure() >>> fig, axs = plt.subplots(1,2) >>> axs[0].imshow(img, cmap='gray'); axs[0].set_title('Input') >>> axs[1].imshow(img_filtered, cmap='gray'); axs[1].set_title('Median filter')