Canny Edge Detection OpenCV Python

Canny Edge Detection OpenCV Python

In this blog, we will learn the edge detection in OpenCV Python using Canny’s edge detection algorithm. Edge Detection has great importance in computer vision.

Edge Detection deals with the contours of an image that is usually denoted in an image as an outline of a particular object.

There’s a lot of edge detection algorithms like Sobel, Laplacian, and Canny.

The Canny Edge Detection algorithm is the most commonly used for ease of use as well as the degree of accuracy.

Imports for Canny Edge Detection OpenCV Algorithm

import cv2 as cv

import numpy as np

from matplotlib import pyplot as plt

Composition of Canny Edge Detection

The Canny edge detection OpenCV algorithm is composed of 5 steps:

  1. Noise Reduction – If noise is not removed it may cause the image to detect incorrect edges.
  2. Gradient Calculation
  3. Non-maximum Suppressions
  4. Double threshold
  5. Edge Tracking by Hysteresis

Canny Edge Detection Code

First of all, the image is loaded into a variable using the OpenCV function cv.imread(). The image is loaded in Gray Scale as edges can be easily identified in a grayscale image.

The canny() function takes 3 parameters from the user.

First the image, then the threshold value for first and second.

The Edge Detection relies on the threshold values and so the values are identified by shuffling the threshold values together.

After canny edge detection is over we store the title and images in separate arrays and display using plt.subplot() function present in the matplotlib library.

def canny():

    img = cv.imread("./img/image.jpg", 0)
    canny = cv.Canny(img, 150, 200)

    title = ["Original Image", "Canny"]
    images = [img, canny]

    for i in range(len(images)):
        plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray')
        plt.xticks([]), plt.yticks([])

Edge Detected Image

Canny Edge Detection OpenCV Python
Canny Edge Detection

Learn More Python OpenCV topics like lane detection OpenCV python, line detection, transition effect, etc.

Get full source code of all opencv projects from the github page.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *