The sample source code below shows how to do fast peak detection of 2D array/image. The algorithm uses a *generic non-maximum suppression* to eliminate local minima.

This method is applicable to many tasks in digital signal analysis as the next step in finding the most significant results.

Algorithms such as Hough transform and Harris corners detection often require post-processing to isolate the dominant regions of interest. The proposed implementation of peak detector helps to achieve this.

## Source Code

For better performance, the algorithm uses separable non-maximum suppression. In addition, it can search for peak points in parallel and this makes it suitable for GPU implementations.

```
precision mediump float;
#define KERNEL_SIZE %kernelSize%
// our texture
uniform sampler2D u_image;
uniform vec2 u_textureSize;
uniform vec2 u_direction;
#define GET_PIXEL(_p) (texture2D(u_image, textCoord + onePixel*float(_p)))
void main() {
vec2 onePixel = u_direction / u_textureSize;
vec2 textCoord = gl_FragCoord.xy / u_textureSize;
if (any(lessThan(GET_PIXEL(0).rgb, vec3(0.0))))
{
gl_FragColor = vec4(vec3(0.0), 1.0);
}
else
{
int maxIndex = KERNEL_SIZE;
float maxValue = 0.0;
for (int i = -KERNEL_SIZE; i <= KERNEL_SIZE; i++)
{
vec3 color = GET_PIXEL(i).rgb;
float p = dot(color, color);
if (p > maxValue)
{
maxValue = p;
maxIndex = i;
}
}
vec4 color = GET_PIXEL(maxIndex);
gl_FragColor = ((maxIndex == 0) ? color : vec4(vec3(-color.rgb)*u_direction.y, 1.0));
}
}
```

## Description

The following steps briefly describe the above source code:

- First, we define the constant “KERNEL_SIZE” so that it is equal to the maximum distance between the peaks;
- For each row in the image we use a sliding window with the defined size. At each step we invert all non-maximum values to a negative number;
- Next we handle the non-maximum values per each column in the same was as in the previous step.
- Pixels with negative value are set to zero

## Online Example

You can try the proposed algorithm right here on our online computer vision test page.

## Other Algorithms

Visit FivekoGFX project for complete source code.