GLSL shader example

Sobel Edge Detection Shader

Two Sobel kernels estimate horizontal and vertical luminance changes. Gradient magnitude is bright at edges and dark in flat regions.

Live example

Edit the code and the preview updates as you type.

What to observe

Sobel Edge Detection Shader.

Mechanism

Two Sobel kernels estimate horizontal and vertical luminance changes. Gradient magnitude is bright at edges and dark in flat regions.

The controlling code

vec2 px=vec2(1.+u_parameter*3.)/256.;float gx=0.,gy=0.;for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++){float l=dot(texture2D(u_texture,uv+vec2(float(x),float(y))*px).rgb,vec3(.299,.587,.114));gx+=l*float(x)*(y==0?2.:1.);gy+=l*float(y)*(x==0?2.:1.);}c=vec3(length(vec2(gx,gy)));

Experiment

Set u_parameter to 0 and then 1, changing px=vec2(1.+u_parameter*3.)/256. from one to four texture pixels. Wider sample spacing makes the grid and letter edges spread over a larger region.

Debugging and cost

Nine source reads are shared by gx and gy before length(vec2(gx,gy)) combines them. Replace that final length with abs(gx) to inspect only horizontal brightness changes; many horizontal lines then lose their response.

Understand the technique

Built-in functions used

Learn it step by step