Skip to content

Instantly share code, notes, and snippets.

@Hebali
Created January 12, 2017 17:25
Show Gist options
  • Save Hebali/6ebfc66106459aacee6a9fac029d0115 to your computer and use it in GitHub Desktop.
Save Hebali/6ebfc66106459aacee6a9fac029d0115 to your computer and use it in GitHub Desktop.
GLSL Fragment Shader: Sobel Edge Detection
// Sobel Edge Detection Filter
// GLSL Fragment Shader
// Implementation by Patrick Hebron
uniform sampler2D texture;
uniform float width;
uniform float height;
void make_kernel(inout vec4 n[9], sampler2D tex, vec2 coord)
{
float w = 1.0 / width;
float h = 1.0 / height;
n[0] = texture2D(tex, coord + vec2( -w, -h));
n[1] = texture2D(tex, coord + vec2(0.0, -h));
n[2] = texture2D(tex, coord + vec2( w, -h));
n[3] = texture2D(tex, coord + vec2( -w, 0.0));
n[4] = texture2D(tex, coord);
n[5] = texture2D(tex, coord + vec2( w, 0.0));
n[6] = texture2D(tex, coord + vec2( -w, h));
n[7] = texture2D(tex, coord + vec2(0.0, h));
n[8] = texture2D(tex, coord + vec2( w, h));
}
void main(void)
{
vec4 n[9];
make_kernel( n, texture, gl_TexCoord[0].st );
vec4 sobel_edge_h = n[2] + (2.0*n[5]) + n[8] - (n[0] + (2.0*n[3]) + n[6]);
vec4 sobel_edge_v = n[0] + (2.0*n[1]) + n[2] - (n[6] + (2.0*n[7]) + n[8]);
vec4 sobel = sqrt((sobel_edge_h * sobel_edge_h) + (sobel_edge_v * sobel_edge_v));
gl_FragColor = vec4( 1.0 - sobel.rgb, 1.0 );
}
@C1nemaclub
Copy link

What are you using the make_kernel for? in the void main

@oreznicek
Copy link

What are you using the make_kernel for? in the void main

The make_kernel function is used to create a matrix (kernel) of surrounding pixels (1 pixel and 8 pixels around = 9 pixels in total).
n[4] is the original pixel

The w and h is the width and height of one pixel represented using UV coordinates.
Using those two you can modify the UV coordinates to point to the surrounding pixels.

After you get the kernel you can apply the sobel filter, which is done by kernel convolution, but he just does that manually in this example.

I hope this helps :)

@C1nemaclub
Copy link

It sure does, thanks for answering

@Deepak-Sangle
Copy link

How do you calculate the width and height of a pixel?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment