The Wayback Machine - https://web.archive.org/web/20240624211205/https://www.geeksforgeeks.org/real-time-edge-detection-using-opencv-python/
Open In App

Real-Time Edge Detection using OpenCV in Python | Canny edge detection method

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video is continuously captured and each frame is processed by edge detection algorithms which identify and highlight these edges continuously.

In this article, we will use the Canny edge detection algorithms of OpenCV to detect the edges in real-time. It is one of the most widely used edge detection algorithms. Let’s understand the Canny edge detection in depth.

Canny Edge Detection

Canny Edge Detection is one of the most widely used edge detection algorithms developed by John F. Canny in 1986. It works in four stages i.e Noise reduction, Finding the intensity gradient, Non-maximum suppression, and Hysteresis thresholding.

Let’s understand each stage one by one:

Step 1: Noise Reduction

First, the noise in the image is reduced by blurring the image. To blur the image we apply the Gaussian filter. It applies a weighted average to each pixel, which reduces the sensitivity with the slight changes in intensity caused by noise. The larger the kernel size, the more significant the smoothing effect. The formula for a 2D Gaussian kernel is given by:

G(x,y) = \frac{1}{2\pi\sigma^2}e^{-\frac{x^2+y^2}{2\sigma^2}}

Step 2: Finding the intensity gradient

In this step, the intensity gradient of the image is found, which helps to locate the areas of sudden intensity shifts that correspond to edges in the image. The technique, known as Sobel algorithms are used to compute the first derivative of the image in both the horizontal (Gx) and vertical (Gy) directions. The horizontal gradient (Gx) and vertical gradient (Gy) are given by the following convolution operations:

G_x= \begin{bmatrix}  -1& 0 & 1 \\  -2 & 0 & 2\\  -1 & 0 & 1 \end{bmatrix}  \\ G_y = \begin{bmatrix}  -1& -2 & -1 \\  0 & 0 & 0\\  1 & 2 & 1 \end{bmatrix}

The following equations can be used to calculate the gradient’s intensity (G) and direction (θ) at each pixel:

G = \sqrt{G_{x}^{2} + G_{y}^{2}}  \\ \text{Angle}(\theta) = \tanh^{-1} {\left(\frac{G_y}{G_x}\right)}

The gradient direction will be always perpendicular to the edges.

Step 3: Non-maximum Suppression

We use non-maximum suppression to get thin edges. Each pixel is looked at in the gradient direction to see if there is a local maximum. If it isn’t, the pixel is suppressed (its value is set to 0) because it probably isn’t a component of an edge.

Step 4: Hysteresis Thresholding

Hysteresis thresholding is used to finalize the edges. We set the minVal and maxVal threshold values. Pixels with gradient magnitudes above maxVal are considered strong edges, while those below minVal are considered non-edges and discarded. Pixels with magnitudes between minVal and maxVal are considered weak edges.

To identify the final edges, we follow the strong edges and consider weak edges connected to them as part of the edge. If a weak edge is not connected to any strong edge, it is discarded as noise.

Implementations:

Canny Edge Detection

Python3

import cv2
  
def canny_edge_detection(frame):
    # Convert the frame to grayscale for edge detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      
    # Apply Gaussian blur to reduce noise and smoothen edges
    blurred = cv2.GaussianBlur(src=gray, ksize=(3, 5), sigmaX=0.5)
      
    # Perform Canny edge detection
    edges = cv2.Canny(blurred, 70, 135)
      
    return blurred, edges

                    

Code explantions

The frame is a single image frame (numpy array) on which we will perform edge detection using the Canny edge detection method.

# Convert the frame to grayscale for edge detection
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

This line converts the input frame from the BGR colour space to grayscale. The Canny edge detection method works on grayscale images, so we first convert the frame to grayscale using cv2.cvtColor() the function.

# Apply Gaussian blur to reduce noise and smoothen edges 
blurred = cv2.GaussianBlur(src=gray, ksize=(3, 5), sigmaX=0.5)

This line applies Gaussian blur to the grayscale image. The cv2.GaussianBlur() function helps to reduce noise and smoothens the edges, which is useful for obtaining better edge detection results. The (3, 5) argument represents the size of the Gaussian kernel used for blurring and 0 indicates the standard deviation in the X and Y directions.

# Perform Canny edge detection
edges = cv2.Canny(blurred, 70, 135)

This line performs the actual Canny edge detection on the blurred grayscale image. The cv2.Canny() the function takes three arguments: the input image (blurred), the lower threshold (70), and the upper threshold (135). Pixels with gradient magnitude below the lower threshold are considered not edges, and pixels with gradient magnitude above the upper threshold are considered strong edges. Pixels with gradient magnitude between the two thresholds are considered weak edges.

Real-Time Edge Detection

Python3

def main():
    # Open the default webcam 
    cap = cv2.VideoCapture(0)
      
    while True:
        # Read a frame from the webcam
        ret, frame = cap.read()
        if not ret:
            print('Image not captured')
            break
          
        # Perform Canny edge detection on the frame
        blurred, edges = canny_edge_detection(frame)
          
        # Display the original frame and the edge-detected frame
        #cv2.imshow("Original", frame)
        cv2.imshow("Blurred", blurred)
        cv2.imshow("Edges", edges)
          
        # Exit the loop when 'q' key is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
      
    # Release the webcam and close the windows
    cap.release()
    cv2.destroyAllWindows()

                    

Apply the Real-Time Edge Detection

Python3

if __name__ == "__main__":
    main()

                    

Output:

Canny edge detection-Geeksforgeeks

Conclusion

The Canny Edge Detection algorithm provides accurate and robust edge detection by suppressing noise, finding the gradient magnitude and direction, and applying hysteresis thresholding. It has wide applications in computer vision tasks such as object detection, image segmentation, and feature extraction. By implementing this algorithm with the OpenCV library in Python, we can achieve real-time edge detection from live video feeds or webcam streams, enabling us to build various computer vision applications.



Previous Article
Next Article

Similar Reads

Implement Canny Edge Detector in Python using OpenCV
In this article, we will learn the working of the popular Canny edge detection algorithm developed by John F. Canny in 1986. Usually, in Matlab and OpenCV we use the canny edge detection for many popular tasks in edge detection such as lane detection, sketching, border removal, now we will learn the internal working and implementation of this algor
5 min read
Python OpenCV - Canny() Function
In this article, we will see the Canny Edge filter in OpenCV. Canny() Function in OpenCV is used to detect the edges in an image. Syntax: cv2.Canny(image, T_lower, T_upper, aperture_size, L2Gradient) Where: Image: Input image to which Canny filter will be appliedT_lower: Lower threshold value in Hysteresis ThresholdingT_upper: Upper threshold value
3 min read
Multiple Color Detection in Real-Time using Python-OpenCV
For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important. Why this is important? : Some Real-world Applications In self-driving car, to detect the traffic signals. Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating d
4 min read
Real time object color detection using OpenCV
In this article, we will discuss how to detect a monochromatic colour object using python and OpenCV. Monochromatic color means light of a single wavelength. We will use the video, captured using a webcam as input and try to detect objects of a single color, especially Blue. But you can detect any color if you set the range properly, we'll discuss
4 min read
OpenCV | Real Time Road Lane Detection
Autonomous Driving Car is one of the most disruptive innovations in AI. Fuelled by Deep Learning algorithms, they are continuously driving our society forward and creating new opportunities in the mobility sector. An autonomous car can go anywhere a traditional car can go and does everything that an experienced human driver does. But it's very esse
15+ min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Wand canny() function - Python
The canny() function is an inbuilt function in the Python Wand ImageMagick library which is used to detect edges by leveraging a multi-stage Canny algorithm. Syntax: canny(radius, sigma, lower_percent, upper_percent) Parameters: This function accepts two parameters as mentioned above and defined below: radius: This parameter stores the radius of th
2 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Python OpenCV - Roberts Edge Detection
Edge detection refers to a set of mathematical techniques for recognizing points in a digital image where the image brightness abruptly changes or, more formally, where there are discontinuities. The sharp fluctuations in image brightness are usually grouped into a collection of curved line segments called edges. Roberts Edge DetectionThe Roberts o
3 min read
Practice Tags :
three90RightbarBannerImg