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

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:

sudo apt-get install libopencv-dev python-opencv

bash install-opencv.sh

Principle behind Edge Detection

Edge detection involves mathematical methods to find points in an image where the brightness of pixel intensities changes distinctly.

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

import cv2

import numpy as np

cap = cv2.VideoCapture( 0 )

while ( 1 ):

`` _, frame = cap.read()

`` hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

`` sobelx = cv2.Sobel(frame,cv2.CV_64F, 1 , 0 ,ksize = 5 )

`` sobely = cv2.Sobel(frame,cv2.CV_64F, 0 , 1 ,ksize = 5 )

`` 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()

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.

Convolving an image with a kernel

Parameters:

cv2.Sobel(original_image,ddepth,xorder,yorder,kernelsize)

cv2.Laplacian(frame,cv2.CV_64F)

Edge Detection Applications

Related Article: Edge Detection using Canny edge detection method