Dec 6, 2011

Canny Edge Detection using fragment shader

I implemented the canny edge detection on the iPhone with GLSL in the fragment shader. I got a lot of help from this paper http://www.dip.ee.uct.ac.za/prasa/PRASA2010/proceedings/2007/prasa07-26.pdf
And also from this GPU gem:
http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter40.html
So basically the fragment shader looks like this:

float4 CannySearch(

  uniform float4 thresh,

  float2 fptexCoord : TEXCOORD0,

  uniform samplerRECT FPE1 ) : COLOR

{

  // magdir holds { dx, dy, mag, direct }



  float4 magdir = texRECT(FPE1, fptexCoord);

  float alpha = 0.5/sin(3.14159/8); // eight directions on grid



  float2 offset = round( alpha.xx * magdir.xy/magdir.zz );



  float4 fwdneighbour, backneighbour;

  fwdneighbour = texRECT(FPE1, fptexCoord + offset );

  backneighbour = texRECT(FPE1, fptexCoord + offset );



  float4 colorO;

  if ( fwdneighbour.z > magdir.z || backneighbour.z > magdir.z )

    colorO = float4(0.0, 0.0, 0.0, 0.0); // not an edgel



  else

    colorO = float4(1.0, 1.0, 1.0, 1.0); // is an edgel

  if ( magdir.z < thresh.x )

    colorO  = float4(0.0, 0.0, 0.0, 0.0); // thresholding



  return colorO;

}

And this works pretty well on the iPhone. I assigned each contour with different colors, so the edge looks more distinct:

1 comment:

e said...

Could you upload a example project using this shader? I'm new to iOS programing and to GLSL. It would be very helpful having a working simple project.

Thanks.