Python OpenCV Canny() Function (original) (raw)

Last Updated : 23 Apr, 2025

**Canny edge detection algorithm is used in computer vision for identifying edges within an image. It helps in highlighting boundaries which are important for tasks like object detection and image segmentation. In this article, we will see how OpenCV’s built-in**Canny()**function detects edges in an image.

**Syntax: cv2.Canny(image, T_lower, T_upper, aperture_size, L2Gradient)

**Where:

**Return Value: Returns an image with detected edges where edges are marked in white (255) and non-edges in black (0).

1. Using Canny() Function

**Input Image:

import cv2 img = cv2.imread("test.jpeg") t_lower = 50
t_upper = 150 edge = cv2.Canny(img, t_lower, t_upper) cv2.imshow('original', img) cv2.imshow('edge', edge) cv2.waitKey(0) cv2.destroyAllWindows()

`

**Output:

2. Canny() function with Aperture_size

This is optional parameter that is used to specify the order of the Sobel filter used to calculate gradient in the Canny algorithm. We can increase Aperture size when we want to detect more detailed features.

import cv2 img = cv2.imread("test.jpeg") t_lower = 100
t_upper = 200
aperture_size = 5 edge = cv2.Canny(img, t_lower, t_upper, apertureSize=aperture_size) cv2.imshow('original', img) cv2.imshow('edge', edge) cv2.waitKey(0) cv2.destroyAllWindows()

`

**Output:

3. Canny() function with L2Gradient

It’s a boolean parameter that specifies if we want to calculate usual gradient equation or the L2Gradient algorithm.

import cv2 img = cv2.imread("test.jpeg") t_lower = 100 t_upper = 200 aperture_size = 5 L2Gradient = True edge = cv2.Canny(img, t_lower, t_upper, L2gradient = L2Gradient ) cv2.imshow('original', img) cv2.imshow('edge', edge) cv2.waitKey(0) cv2.destroyAllWindows()

`

Output:

4. Canny() function with both Aperture size and L2gradient

Here we will use both attributes within the same function.

Python `

import cv2 img = cv2.imread("test.jpeg") t_lower = 100 t_upper = 200 aperture_size = 5 L2Gradient = True edge = cv2.Canny(img, t_lower, t_upper, apertureSize = aperture_size, L2gradient = L2Gradient ) cv2.imshow('original', img) cv2.imshow('edge', edge) cv2.waitKey(0) cv2.destroyAllWindows()

`

**Output:

With the flexibility of the **Canny() function we can experiment with different parameters to effectively detect edges and enhance the details in our images.