Python library for the detection of peaks and valleys.

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=3)

Python library for the detection of peaks and valleys.

findpeaks is for the detection and vizualization of peaks and valleys in a 1D-vector and 2D-array. In case of 2D-array, the image can be pre-processed by resizing, scaling, and denoising. For a 1D-vector, pre-processing by interpolation is possible. Peaks can be detected using various methods, and the results can be vizualized, such as the preprocessing steps, the persistence of peaks, the masking plot and a 3d-mesh plot.

Examples

>>> from findpeaks import findpeaks
>>> 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
>>> from findpeaks import findpeaks
>>> X = fp.import_example('2dpeaks')
>>> results = fp.fit(X)
>>> fp.plot()
>>>
>>> # Image example
>>> from findpeaks import findpeaks
>>> fp = findpeaks(method='topology',imsize=(300,300),denoise='fastnl',params={'window': 30})
>>> X = fp.import_example('2dpeaks_image')
>>> results = fp.fit(X)
>>> fp.plot()
>>>
>>> # Plot each seperately
>>> fp.plot_preprocessing()
>>> fp.plot_persistence()
>>> fp.plot_mesh()

References

fit(X, x=None)

Detect peaks and valleys in a 1D vector or 2D-array (image).

Description

  • Fit the method on your data for the detection of peaks.

  • See 1dpeaks and 2dpeaks for more details about the input/output parameters.

param X:

Input data.

type X:

array-like data.

param x:

Coordinates of the x-axis.

type x:

array-like data.

returns:
  • See 1dpeaks and 2dpeaks for more details.

rtype:

dict()

import_example(data='2dpeaks', url=None, sep=';', datadir=None)

Import example dataset from github source.

Description

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 Verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type Verbose:

int (default : 3)

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, verbose=3)

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 of peaks in 1D array.

Description

This function only eats the input data. Use the .fit() function for more information regarding the input parameters:
  • method : Method to be used for peak detection: ‘topology’ or ‘peakdetect’.

  • lookahead : Looking ahead for peaks. For very small 1d arrays (such as up to 50 datapoints), use low numbers: 1 or 2.

  • interpolate : Interpolation factor. The higher the number, the less sharp the edges will be.

  • limit : Values > limit are set as regions of interest (ROI).

  • verbose : Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

  • height: Required height of the peaks.

param X:

Input data.

type X:

array-like 1D vector.

param x:

Coordinates of the x-axis.

type x:

array-like 1D vector.

returns:
  • dict() (Results in “df” are based on the input-data, whereas “df_interp” are the interpolated results.) –

    • persistence : Scores when using topology method.

    • Xranked : Similar to column “rank”.

    • Xdetect : Similar to the column “score”.

    • df : Is ranked in the same manner as the input data and provides information about the detected peaks and valleys.

  • persistence (pd.DataFrame()) –

    • x, y : Coordinates

    • birth : Birth level

    • death : Death level

    • score : Persistence scores

  • df (pd.DataFrame()) –

    • x, y : Coordinates

    • labx : The label of the peak area

    • rank : The ranking number of the best performing peaks (1 is best)

    • score : Persistence score

    • valley : Whether the point is marked as valley

    • peak : Whether the point is marked as peak

Examples

>>> from findpeaks import findpeaks
>>> 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()
>>>
>>> fp = findpeaks(method='topology')
>>> results = fp.fit(X)
>>> fp.plot()
>>> fp.plot_persistence()
peaks2d(X, method='topology')

Detect peaks and valleys in a 2D-array or image.

Description

To handle 2D-arrays or images. Use the .fit() function for more information regarding the input parameters:
  • method : Method to be used for peak detection: ‘topology’, or ‘mask’

  • limit : Values > limit are set as regions of interest (ROI).

  • scale : Scaling data in range [0-255] by img*(255/max(img))

  • denoiseRemove noise using method:
    • None

    • ‘fastnl’

    • ‘bilateral’

    • ‘lee’

    • ‘lee_enhanced’

    • ‘lee_sigma’

    • ‘kuan’

    • ‘frost’

    • ‘median’

    • ‘mean’

  • window : Denoising window.

  • cu : Noise variation coefficient.

  • togray : Conversion to gray scale.

  • imsize : Resize image.

  • verbose : Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

param X:

Input data.

type X:

array-like 1D vector.

returns:
  • Xraw : The RAW input data

  • Xproc : The pre-processed data

  • Xdetect : The detected peaks with the persistence scores (same shape as the input data)

  • XRanked : The detected peaks but based on the strenght (same shape as the input data)

  • persistencepd.DataFrame()
    • x, y : Coordinates

    • birth : Birth level

    • death : Death level

    • score : Persistence scores

rtype:

dict()

Examples

>>> # 2D array example
>>> from findpeaks import findpeaks
>>> X = fp.import_example('2dpeaks')
>>> results = fp.fit(X)
>>> fp.plot()
>>>
>>> # Image example
>>> from findpeaks import findpeaks
>>> X = fp.import_example('2dpeaks_image')
>>> fp = findpeaks(imsize=(300,300),denoise='fastnl',params={'window': 30})
>>> results = fp.fit(X)
>>> fp.plot()
>>>
>>> # Plot each seperately
>>> fp.plot_preprocessing()
>>> fp.plot_persistence()
>>> fp.plot_mesh()
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')

Plot results.

Parameters:
  • legend (bool, (default: True)) – Show the legend.

  • figsize ((int, int), optional, default: (15, 8)) – (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. None: Automatically sizes based on peak value

  • marker (str (default: 'x')) – Marker type.

  • color (str (default: '#FF0000')) – Hex color of the marker.

Returns:

fig_axis

Return type:

tuple containing (fig, ax)

plot1d(legend=True, figsize=None, xlabel='x-axis', ylabel='y-axis')

Plot the 1D results.

Parameters:
  • legend (bool, (default: True)) – Show the legend.

  • figsize ((int, int), (default: None)) – (width, height) in inches.

Returns:

fig_axis

Return type:

tuple containing axis for each figure.

plot2d(figsize=None, limit=None, figure_order='vertical')

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')

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.

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’

  • verbose (int (default : 3)) – Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

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', verbose=None)

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.

  • verbose (int (default : 3)) – Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

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)

Preprocessing steps of the 2D array (image).

The pre-processing has 4 (optional) steps.
  1. Resizing (to reduce computation time).

  2. Scaling color pixels between [0-255].

  3. Conversion to gray-scale. This is required for some analysis.

  4. Denoising of the image.

Parameters:
  • X (numpy-array) – Input data or image.

  • showfig (bool) – Show the preocessing steps in figures. The default is None.

Returns:

X – Processed image.

Return type:

numpy-array

findpeaks.findpeaks.import_example(data='2dpeaks', url=None, sep=';', verbose=3, datadir=None)

Import example dataset from github source.

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 Verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type Verbose:

int (default : 3)

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.stats.denoise(X, method='fastnl', window=9, cu=0.25, verbose=3)

Denoise input data.

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)

param verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type verbose:

int (default: 3)

returns:

X – Denoised data.

rtype:

array-like

References

findpeaks.stats.disable_tqdm(verbose)

Set the verbosity messages.

findpeaks.stats.mask(X, limit=0, verbose=3)

Determine peaks in 2d-array using a mask.

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, verbose=3)

Resize image.

Parameters:
  • X (array-like) – Input image data.

  • size (tuple, (default: None)) – size to desired (width,length).

  • verbose (int (default: 3)) – Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

Returns:

X

Return type:

array-like

findpeaks.stats.reverse_values(image_array)
findpeaks.stats.scale(X, verbose=3)

Normalize data (image) by scaling.

Description

Scaling in range [0-255] by img*(255/max(img))

param X:

Input image data.

type X:

array-like

param verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type verbose:

int (default: 3)

returns:

X – Scaled image.

rtype:

array-like

findpeaks.stats.togray(X, verbose=3)

Convert color to grey-image.

Description

Convert 3d-RGB colors to 2d-grey image.

param X:

Input image data.

type X:

array-like

param verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type verbose:

int (default: 3)

returns:

X – 2d-image.

rtype:

array-like

findpeaks.stats.topology(X, limit=None, reverse=True, verbose=3)

Determine peaks using toplogy method.

Description

The idea behind the topology method: Consider the function graph of the function that assigns each pixel its level. Now consider a water level that continuously descents to lower levels. At local maxima islands pop up (birth). At saddle points two islands merge; we consider the lower island to be merged to the higher island (death). The so-called persistence diagram (of the 0-th dimensional homology classes, our islands) depicts death- over birth-values of all islands. The persistence of an island is then the difference between the birth- and death-level; the vertical distance of a dot to the grey main diagonal. The figure labels the islands by decreasing persistence. This method not only gives the local maxima but also quantifies their “significance” by the above mentioned persistence. One would then filter out all islands with a too low persistence. However, in your example every island (i.e., every local maximum) is a peak you look for.

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 verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type verbose:

int (default: 3)

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()
  • x, y: Coordinates

  • birth: Birth level, tuple(coordinate, rgb value)

  • death: Death level, tuple(coordinate, rgb value)

  • score: Persistence scores

rtype:

dict()

References

findpeaks.stats.topology2d(X, limit=None, whitelist=['peak', 'valley'], verbose=3)

Determine peaks and valleys in 2d-array using toplogy method.

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)

param verbose:

Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

type verbose:

int (default: 3)

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, verbose=3)

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.

  • verbose (int (default : 3)) – Print to screen. 0: None, 1: Error, 2: Warning, 3: Info, 4: Debug, 5: Trace.

Returns:

X – Interpolated data.

Return type:

array-like (1D-vector)

findpeaks.interpolate.interpolate_line2d(xs, ys=None, interpol=3, window=3, verbose=3)

interpolate 2D vector.

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)

param verbose:

Print information to screen. A higher number will print more.

type verbose:

int [1-5], 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, verbose=3)

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’

  • verbose (int ( default is 3)) – Print message to screen. A higher number will increase outputs.

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.

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.

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.

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:

  • k: in [0:10]

  • cu: positive

  • cmax: 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.

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.

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.

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')