Mastering Canny Edge Detection with OpenCV: A Comprehensive Guide

Guillaume Demarcq
Canny edge detection using Ikomia API

In this case study, we will explore how to implement Canny edge detection with OpenCV. By following the step-by-step process, we will be able to create a Canny edge detection workflow and analyze the results.

The Ikomia API simplifies the development of Computer Vision workflows and provides easy experimentation with different parameters to achieve optimal results. 

Get started with Ikomia API

You can easily create a Canny edge detection workflow with just a few lines of code. All you need to do is install the API in a virtual environment.

How to install a virtual environment

pip install ikomia

API documentation

API repo

Run the Canny edge detection algorithm with a few lines of code using Ikomia API

You can also charge directly the open-source notebook we have prepared.

For a step-by-step detailed approach jump to this section.

from ikomia.dataprocess.workflow import Workflow
from ikomia.utils.displayIO 
import display

# Init your workflow
wf = Workflow()

# Add the Canny Edge Detector
canny = wf.add_task(ik.ocv_canny(), auto_connect=True)

# Run on your image    
# wf.run_on(path="path/to/your/image.png")

# Inspect your results

example image with computers on the table, before edge detection is applied
example image with computers on the table, after edge detection is applied

On top, you see the original input image. And underneath, you see the output image, commonly known as the edge map.

How does the Canny Edge detection work?

Learn more about Canny edge detection in OpenCV.

Edge detection is an essential image processing technique commonly employed in various computer vision applications, including data extraction, image segmentation, feature extraction, and pattern recognition.

This technique helps reduce the amount of noise and irrelevant details in an image while retaining its structural information. As a result, edge detection plays a crucial role in enhancing the accuracy and performance of computer vision algorithms.

Whether you're working on object detection, image recognition, or other Computer Vision tasks, edge detection is a critical step in your workflow.

Canny edge detection is widely regarded as one of the most popular and effective methods for edge detection in Computer Vision. It employs a multi-stage algorithm to detect a wide range of edges in images. This algorithm can be broken down into four basic steps:

Noise reduction

The first step in Canny edge detection involves preprocessing the image to remove any noise or blur. This is usually achieved by applying a Gaussian filter to smooth the image. 

example image after gaussian filter has been applied

Gradient calculation

The second step calculates the image's gradient by applying Sobel filters in the x and y directions to get the derivatives Gx and Gy. These derivatives provide the gradient intensity matrix and gradient angles, which help identify regions with significant intensity changes, indicating edges.

example image after gradient calculation sobel filters has been applied

Non-maximum suppression

In the third step, the algorithm thins out the edges by suppressing any non-maximum gradient pixels. Each pixel's gradient magnitude is compared to its neighboring pixels in the gradient direction. If the gradient magnitude is not the highest in that direction, the pixel is suppressed, and the edge is thinned resulting in a one-pixel-wide edge representation.

example image after edges have been thinned down

Hysteresis thresholding

The final step determines which edges to keep and discard. It applies two thresholds: a high threshold and a low threshold. Edge pixels with a gradient magnitude above the high threshold are kept, while those with a gradient magnitude below the low threshold are discarded. Edge pixels with a gradient magnitude between the high and low thresholds are preserved only if they are connected to a strong edge pixel.

example of image after Hysteresis thresholding has been applied

Step by step Canny edge detection with Ikomia API

Now let's dive into the detailed steps of creating Canny edge detection workflows using the Ikomia API.

Step 1: Import

from ikomia.dataprocess.workflow 
import Workflowfrom ikomia.utils.displayIO 
import displayfrom ikomia.utils import ik

  • Workflow is the base class object used to create a workflow object. It provides methods for setting image, video and directory inputs, setting task parameters, getting time metrics and getting specific task outputs defined by their types (graphics, segmentation masks, texts…).
  • The display function allows for flexible and customizable image (input/output) and graphics display, including bounding boxes and segmentation masks and graphics such as bounding boxes, segmentation masks, etc..
  • ik is an auto-completion system designed to conveniently and easily access algorithms and settings.

Step 2: Create workflow

wf = Workflow()

We initialize a workflow instance. The “wf” object can then be used to add tasks to the workflow instance, configure their parameters, and run them on input data.

Step 3: Add the OpenCV Canny algorithm

We can use the ik namespace to search for algorithms.

canny = wf.add_task(ik.ocv_canny(), auto_connect=True)

image of canny search

Step 4: Algorithm settings

The OpenCV Canny edge detection takes several parameters that control its behavior:

  • threshold1: the lower threshold of the hysteresis procedure. Edges with intensity gradients below this value will be discarded.
  • threshold2: the upper threshold value. Edges with intensity gradients above this value will be considered strong edges.
  • apertureSize: the size of the Sobel kernel used for edge detection. This parameter affects the level of detail in the edges detected.
  • L2gradient: a Boolean flag that indicates whether to use the L2 norm for gradient calculation. If set to 1, the algorithm will use the Euclidean distance to calculate the gradient magnitude. If set to 0 (default), the algorithm will use the L1 norm, which is less computationally expensive.

Adjusting these parameters can significantly impact the performance of the Canny edge detection. For example, increasing the threshold values will result in detecting fewer edges, while increasing the aperture size will result in detecting more detailed edges.

Step 5: Setting the parameters

Here, we use the auto-completion to find the names of the available parameters.

canny = wf.add_task(ik.ocv_canny(threshold1="100", threshold2="200", apertureSize="3", L2gradient="0"), auto_connect=True)

Step 6: Apply your workflow on your image

The run_on() function allows you to apply your workflow to the image. For this example, we get our image from an URL:


Step 7: Display your results

Finally, you can display our image results using the display function: 


example image of final result after edge detection is over display results is active

Default parameters:


example image with default display results values

              ik.ocv_canny.apertureSize: "3",

By increasing the threshold1 value, fewer edges are detected

example image with increased threshold value and fewer edges


By increasing the aperture size, more detailed edges can be detected.

Create your own workflow with Ikomia

To learn more about the API, refer to the documentation. You may also check out the list of state-of-the-art algorithms on Ikomia HUB and try out Ikomia STUDIO, which offers a friendly UI with the same features as the API.

No items found.

Build with Python API


Create with STUDIO app