Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to detect the edges of an image using OpenCV | Sobel edge detection method
Next article icon

Python Program to detect the edges of an image using OpenCV | Sobel edge detection method

Last Updated : 04 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
     
Convolving an image with a kernel

  • 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  


Next Article
Python Program to detect the edges of an image using OpenCV | Sobel edge detection method

P

pratima upadhyay
Improve
Article Tags :
  • Python
Practice Tags :
  • python

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
    How to Detect Shapes in Images in Python using 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 also we are going to use
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences