In this article, we will explore how to implement a fast image edge detector using OpenGL shader code.
Edge detection is a crucial component in many image processing algorithms, and achieving quick and optimal performance is essential for effective results.
While our previous articles demonstrated how to implement the Sobel operator using pure JavaScript, this approach may not deliver the best performance, especially for larger images.
With the power of WebGL, we can now create efficient online image processing tools that work seamlessly across various web browsers, significantly enhancing our capabilities and user experience.
OpenGL source code
precision mediump float;
#define KERNEL_SIZE 3
// our texture
uniform sampler2D u_image;
uniform vec2 u_textureSize;
uniform float u_kernel[KERNEL_SIZE];
#define M_PI 3.141592654
#define GET_PIXEL(_x, _y) (texture2D(u_image, textCoord + onePixel*vec2(_x, _y)))
void main() {
vec2 onePixel = vec2(1.0, 1.0) / u_textureSize;
vec2 textCoord = gl_FragCoord.xy / u_textureSize;
float dx = (length(GET_PIXEL(-1, -1)*u_kernel[0] +
GET_PIXEL(-1, 0)*u_kernel[1] +
GET_PIXEL(-1, +1)*u_kernel[2]) -
length(GET_PIXEL(+1, -1)*u_kernel[0] +
GET_PIXEL(+1, 0)*u_kernel[1] +
GET_PIXEL(+1, +1)*u_kernel[2]));
float dy = (length(GET_PIXEL(-1, -1)*u_kernel[0] +
GET_PIXEL(0, -1)*u_kernel[1] +
GET_PIXEL(+1, -1)*u_kernel[2]) -
length(GET_PIXEL(-1, +1)*u_kernel[0] +
GET_PIXEL(0, +1)*u_kernel[1] +
GET_PIXEL(+1, +1)*u_kernel[2]));
float theta = (atan(dy, dx) + M_PI) / (2.0*M_PI);
gl_FragColor = vec4(length(vec2(dx, dy)), theta, 0.0, 1.0);
}
Conclusion
In this post, we introduced a straightforward OpenGL shader that leverages the GPU to extract picture contours. The resulting code generates an image that highlights both the gradient strength and orientation, which can then be utilized to achieve thin image contours through non-maximum suppression.
If you found this article helpful, we invite you to explore our collection of image analysis algorithms and visit our software developers portal for more resources and tools.
WEB APPLET
See how it works in the browser!