Canny Edge Detection

Since first exploring the OpenCV in middle school, it always seemed like magic to me that you could use math to track faces, find edges, and so much more. While relatively old, Canny Edge Detection is still a computer vision staple in reducing the amount of data in an image and identifying edges. In this post I explain a little bit of background behind the algorithm and provide code samples so you can implement it yourself.

Trust The Process

Canny Edge Detection is merely a sequence of 5 transformations on a given grayscale image. When learning the algorithm I found it easier to write functions to implement each one separately. However when computation and speed is important, there are more complicated ways to implement them together and speed up the process. Just remember, trust the process.

  • 1 - Gaussian Smoothing

    Use a Gaussian kernel to smooth the image and remove noise.

  • 2 - Estimate Gradients

    At each pixel we use the Sobel operator to guess the strength of an edge at each pixel.

  • 3 - Non-Maximum Supression

    We want to keep only the strongest edges in our image. This reduces noise and allows us to form a crisp fine edge in our final result.

  • 4 - Double Thresholding

    Whats an actual edge and what is noise? We place two hyperparameters to help us classify strong or weak edges.

  • 5 - Edge Tracking

    For the final step we use local neighborhoods to track and keep only the strongest edges in our image. Thanos would be proud.

The Good, The Bad, and The Ugly

Something I very quickly noticed while doing this project is that hyperparemters matter, a lot. In images with a lot of noise (such as the image of this beautiful hike I did in northern Utah) perform pretty poorly compared to images with crisp edges. A great benefit I think however of understanding this algorithm and implementing it by hand is that you have much more control when you need to implement it on a unique dataset. Too much noise? Increase the size of your smoothing kernel and raise the number of iterations. Too many small edges getting lost? Increase the size of your edge neighborhoods. Through implementing this project my confidence increased in my ability to careful construct edge detection models fit to unique distributions of images.

Whats that, you want to do it yourself?

Well then you’re in luck, I’ve created a 8 page guide on how to implement Canny Edge Detection in Python below. I have given code samples, but I’m going to let the reader have the joy of learning to build it end to end themself. Just press the big red button below to go to the pdf, Enjoy!