How to Perform Edge Detection in Python Using OpenCV?

Posted in /  

How to Perform Edge Detection in Python Using OpenCV?
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Here in this Python tutorial, we will perform edge detection in Python using OpenCV methods. We will also build a Python program that finds the edges for a live video. In edge and gradient detection of an image, we find out the boundaries around the object, and it is generally done with the changing intensities between two colors.

    Although edges and gradients are two different concepts in mathematics, in image processing with programming, you can interchangeably use both in many cases.

    Libraries Required

    As we will be processing our image using Python, we assume you have installed Python on your system, and you have the latest or Python 3.4 or a newer version. For this tutorial, we will be using OpenCV to process the image and find edges. You can easily install OpenCV using the following Python pip terminal command:

    pip install opencv-python

    In some parts of our program, we will also be using the Python numpy library, so make sure that it is also installed for your Python environment. Although you do not need to install Numpy separately because when you install opencv-python , it will automatically install numpy for you, just to ensure run the following command on your terminal or command prompt to install numpy:

    pip install numpy

    How to Perform Edge Detection in Python Using OpenCV?

    In OpenCV, there are three methods to detect edges in an image:

    1. Canny Edge Detector .
    2. Laplacian Edge Sharpening.
    3. Sobel Edge Detector .

    We will be using the following birds.jpg image for this tutorial and detecting its object edges:

    Now, open your Python IDE or text editor and start coding.

    1) OpenCV Edge Detection with Canny Edge Detector

    Canny Edge detection is an advanced and multi-level edge detection algorithm. But with OpenCV, you do not have to worry about writing this algorithm from scratch. OpenCV provides the Canny() method, which can detect all the edges of an image.

    Let's start with importing the OpenCV module and loaing our birds.jpg image.

    import cv2 as cv
    
    #load birds image
    image = cv.imread("birds.jpg")

    Our Python script and the birds.jpg image are in the same directory. Thus, we have specified the relative path by just specifying the image name. Next, we convert the loaded BGR image to a grayscale image because a colorful image can have multiple color intensities.

    Therefore, by converting it to grayscale (black and white), we reduce the intensity of the colors between black and white, and it helps in better edge detection.

    #convert to gray image
    gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    cv.cvtColor(image, cv.COLOR_BGR2GRAY) will convert the BGR image to the GrayScale image. You can see the converted GrayScale image with the cv.imshow("Gray Image:", gray_image) statement, and you will see a similar image.

    After converting the image into a GrayScale image, now pass the gray_image to the OpenCV cv.Canny(image, threshold1, thresold2) method. The Canny() method will return all the edges of the image.

    #detect edges
    canny_edges = cv.Canny(gray_image, 120, 150)

    Here, 120 represents the first threshold for the hysteresis procedure, and 150 represents the second threshold for the hysteresis procedure. Next, show the edges using the cv.imshow() method.

    #show edges
    cv.imshow("Canny Edges", canny_edges)
    cv.waitKey(0)

    Output

    When you execute the program, you will see a similar image:

    2) OpenCV Edge Detection with Laplacian Edge Sharpening

    Laplacian is an edge sharpening algorithm, and in OpenCV, we can use this algorithm with the cv.laplacian() method and detect edges in an image. Let's start with importing the required modules followed by loading the image, and like Canny Edges detection, converting the BGR image to GrayScale.

    import cv2 as cv
    import numpy as np
    
    #load birds image
    image = cv.imread("birds.jpg")
    
    #convert to gray image
    gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    Here you can see that we have also imported the numpy module. We will be using it in this program. After converting the BGR image to gray_scale , now detect the gradients or edges of the image using the OpenCV cv.Laplacian(image, depth) method.

    #detect gradients, edges
    lap_edges = cv.Laplacian(gray_image, cv.CV_64F)

    Here, we are detecting the edges or gradient of gray_image , with destination depth cv.CV_64f . The cv.Laplacian() method detects the gradients for black and white, and due to its vector nature, it converts some of its slope to negative, resulting in negative pixels.

    Now, let's set all lap_edges values to absolute using the numpy np.absolute() method, and then convert all those absolute values to an image array using the np.unit8() method. The unit8 is the data type of the image.

    #convert all -ve pixels to positives
    lap_edges = np.uint8(np.absolute(lap_edges))

    Now, show lap_edges with the cv.imshow() method.

    cv.imshow("Laplacian Edges", lap_edges)
    cv.waitKey(0)

    Output

    When you execute the above program, you will see a similar image:

    3) OpenCV Edge Detection with Sobel Edge Detector

    Sobel Edge detection detects the gradient of the image in two directions, X and Y axes. When we detect the gradients in an image using Sobel in the x-direction, we use cv.Sobel(image, cv.CV_64F, 1, 0 ) and, when we detect the gradients in an image using Sobel in the y-direction, we use cv.Sobel(image, cv.CV_64F, 0, 1 ) .

    import cv2 as cv
    import numpy as np
    
    #load birds image
    image = cv.imread("birds.jpg")
    
    #convert to gray image
    gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    
    #detect sobel gradients
    sobel_x_edges = cv.Sobel(gray_image, cv.CV_64F,1, 0)
    sobel_y_edges = cv.Sobel(gray_image, cv.CV_64F,0, 1)
    
    #convert all -ve pixels to positives
    sobel_x_edges = np.uint8(np.absolute(sobel_x_edges))
    sobel_y_edges = np.uint8(np.absolute(sobel_y_edges))
    
    #show images
    cv.imshow("Sobel X Edges", sobel_x_edges)
    cv.imshow("Sobel y Edges", sobel_y_edges)
    
    cv.waitKey(0)

    Output

    When you execute the above program, you will see the following images:

    Edge Detection of a Live Video

    Now you know how to detect the edges in an image. Next, let's write a Python program that can detect edges from a live video of a webcam. As OpenCV is capable of image as well as video processing, we will be using it with the cv.Canny() method to detect edges from a live webcam.

    import cv2 as cv
    
    #start web cam
    capture = cv.VideoCapture(0) # 0 for web-cam
    
    while True:
        #read video frame by frame
        isTrue, frame= capture.read()
    
        canny_edges = cv.Canny(frame, 120, 150)
    
        #show edges Video
        cv.imshow("Edges Video", canny_edges)
    
        #to display real web cam
        # cv.imshow("Real Web Cam",frame )
    
    
        #press e to exit
        if cv.waitKey(20) ==ord("e"):
            break
    
    capture.release()
    capture.destroyAllWindows()

    Output

    Conclusion

    In most cases, you will be using the cv.Canny() method to detect edges in an image. The Laplacian() and Sobel() methods are generally used to detect gradients, and with these two methods, you need to convert the negative pixels to their absolute value using the numpy absolute() method.

    People are also reading:

    Leave a Comment on this Post

    0 Comments