Python Program to detect the edges of an image using OpenCV | Sobel edge detection method
Last Updated :
04 Jan, 2023
The following program detects the edges of frames in a livestream video content. The code will only compile in linux environment. Make sure that openCV is installed in your system before you run the program.
Steps to download the requirements below:
- Run the following command on your terminal to install it from the Ubuntu or Debian repository.
sudo apt-get install libopencv-dev python-opencv
- OR In order to download OpenCV from the official site run the following command:
bash install-opencv.sh
on your terminal.- Type your sudo password and you will have installed OpenCV.
Principle behind Edge Detection
Edge detection involves mathematical methods to find points in an image where the brightness of pixel intensities changes distinctly.
- The first thing we are going to do is find the gradient of the grayscale image, allowing us to find edge-like regions in the x and y direction. The gradient is a multi-variable generalization of the derivative. While a derivative can be defined on functions of a single variable, for functions of several variables, the gradient takes its place.
- The gradient is a vector-valued function, as opposed to a derivative, which is scalar-valued. Like the derivative, the gradient represents the slope of the tangent of the graph of the function. More precisely, the gradient points in the direction of the greatest rate of increase of the function, and its magnitude is the slope of the graph in that direction.
Note: In computer vision, transitioning from black-to-white is considered a positive slope, whereas a transition from white-to-black is a negative slope.
Python
# Python program to Edge detection
# using OpenCV in Python
# using Sobel edge detection
# and laplacian method
import cv2
import numpy as np
#Capture livestream video content from camera 0
cap = cv2.VideoCapture(0)
while(1):
# Take each frame
_, frame = cap.read()
# Convert to HSV for simpler calculations
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Calculation of Sobelx
sobelx = cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5)
# Calculation of Sobely
sobely = cv2.Sobel(frame,cv2.CV_64F,0,1,ksize=5)
# Calculation of Laplacian
laplacian = cv2.Laplacian(frame,cv2.CV_64F)
cv2.imshow('sobelx',sobelx)
cv2.imshow('sobely',sobely)
cv2.imshow('laplacian',laplacian)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
#release the frame
cap.release()
Calculation of the derivative of an image
A digital image is represented by a matrix that stores the RGB/BGR/HSV(whichever color space the image belongs to) value of each pixel in rows and columns.
The derivative of a matrix is calculated by an operator called the Laplacian. In order to calculate a Laplacian, you will need to calculate first two derivatives, called derivatives of Sobel, each of which takes into account the gradient variations in a certain direction: one horizontal, the other vertical.
- Horizontal Sobel derivative (Sobel x): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case.
- Vertical Sobel derivative (Sobel y): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case.
- Convolution is calculated by the following method: Image represents the original image matrix and filter is the kernel matrix.

Factor = 11 - 2- 2- 2- 2- 2 = 3
Offset = 0
Weighted Sum = 124*0 + 19*(-2) + 110*(-2) + 53*11 + 44*(-2) + 19*0 + 60*(-2) + 100*0 = 117
O[4,2] = (117/3) + 0 = 39
So in the end to get the Laplacian (approximation) we will need to combine the two previous results (Sobelx and Sobely) and store it in laplacian.
Parameters:
- cv2.Sobel(): The function cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5) can be written as
cv2.Sobel(original_image,ddepth,xorder,yorder,kernelsize)
- where the first parameter is the original image, the second parameter is the depth of the destination image. When ddepth=-1/CV_64F, the destination image will have the same depth as the source. The third parameter is the order of the derivative x. The fourth parameter is the order of the derivative y. While calculating Sobelx we will set xorder as 1 and yorder as 0 whereas while calculating Sobely, the case will be reversed. The last parameter is the size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
- cv2.Laplacian: In the function
cv2.Laplacian(frame,cv2.CV_64F)
- the first parameter is the original image and the second parameter is the depth of the destination image.When depth=-1/CV_64F, the destination image will have the same depth as the source.
Edge Detection Applications
- Reduce unnecessary information in an image while preserving the structure of image.
- Extract important features of image like curves, corners and lines.
- Recognizes objects, boundaries and segmentation.
- Plays a major role in computer vision and recognition
Related Article: Edge Detection using Canny edge detection method
Similar Reads
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
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,
5 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as
4 min read
Adding borders to the images using Python - OpenCV
Image processing is an interesting field in today's era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc. I
1 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 c
3 min read
OpenCV Python Program to analyze an image using Histogram
In this article, image analysis using Matplotlib and OpenCV is discussed. Let's first understand how to experiment image data with various styles and how to represent with Histogram. Prerequisites: OpenCVmatplotlibImporting image dataimport matplotlib.pyplot as plt #importing matplotlib The image sh
4 min read
How to Detect Shapes in Images in Python using OpenCV?
Prerequisites: OpenCV OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and als
3 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N
2 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two image
2 min read
Python | OpenCV program to read and save an Image
OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. This is cross-platform library, it provides functions that are used in multiple languages. Coming to image processing, OpenCV enables us to perform multiple operations on image, but
2 min read
Erosion and Dilation of images using OpenCV in python
Morphological operations are a set of operations that process images based on shapes. They apply a structuring element to an input image and generate an output image. The most basic morphological operations are two: Erosion and Dilation Basics of Erosion: Erodes away the boundaries of the foreground
2 min read