Edge Detection Example with OpenCV in Python

     Edge detection is a technique in image processing that includes identifying the edges of an image, which are the boundaries between areas with different color intensity. An edge is a sharp shift in color or intensity in a picture that may be used to spot details like object borders, shape, and textures.

    Edge detection algorithms calculate the gradient of an image which describes the changing rate of pixel intensity in an image, and applies different convolution masks to detect edges lines. There are several edge detection methods in image processing. 

    In this tutorial, you'll briefly learn some of the common edge detection methods like Sobel, Canny, and Laplacian. The tutorial covers:

  1. Sobel edge detection
  2. Canny edge detection
  3. Laplacian edge detection
  4. Source code listing

    We'll start by loading the required libraries.


import cv2
from matplotlib import pyplot as plt 
import numpy as np  
   
 

In this tutorial, we need an image file to apply the edge detection methods. The following code shows how to load an image and display it in a plot. Here, you need to change your file path. The image needs to be converted into the grayscale so we load it with grayscale mode.
 

file = "/Users/user/Desktop/sign.jpg"
 
# Load an image
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
 
plt.imshow(img)
plt.show() 
 
 
 We apply blur effect to decrease noises in image.


# Apply Gaussian blur to remove noise
img_blur = cv2.GaussianBlur(img, (3, 3), 0
   


Sobel edge detection
 
    Sobel operator is used to calculate the gradient magnitude of an image in this method. Sobel edge detection applies two different filters to the image in the horizontal and vertical dimensions, and then combines both outputs to create an edge map. We can use built-in cv2.Sobel() function to perform Sobel edge detection. 
    Below code shows how to use Sobel function and find the edges of an image.
 
 
# Apply Sobel edge detection in the x and y directions
sobelx = cv2.Sobel(img_blur, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(img_blur, cv2.CV_64F, 0, 1, ksize=3)

# Combine the two gradients to produce an edge map
sobel = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0) 
 
plt.imshow(sobel, cmap='gray')
plt.title('Sobel edge detection')
plt.show() 
   

    In this example, first we'll apply Sobel funtion in the x and y directions and combine the gradients to create an edge map. 


Canny edge detection

    Canny edge detection technique involves applying a number of filters to smooth the image and then calculates the gradient magnitude to identify the edges in an image. OpenCV provides a built-in function called cv2.Canny() that can be used to perform edge detection. Below code shows how to apply Canny method. 

    In this example, we provide target image, and indicate a lower and an upper threshold parameters.

 
# Apply Canny edge detection 
canny = cv2.Canny(img_blur, 100, 200)

# display the image
plt.imshow(canny)
plt.title('Canny edge detection')
plt.show() 
  

 

 Laplacian edge detection

    Another gradient-based edge detection method is called Laplacian edge detection that works by calculating an image's second-order derivative using the Laplacian operator to detect edges and other features in an image. Laplacian edge detection is more susceptible to noise than the other edge detection methods and may produce inaccurate edges. 
    We can use OpenCV's cv2.Laplacian() function to perform Laplacian edge detection. Here is an example of using Laplacian() operator. To improve the edge quality and control the noise level, we need to adjust the threshold level. 
 
 
# Apply Laplacian edge detection
laplacian = cv2.Laplacian(img_blur, cv2.CV_64F)

# Threshold the edge map, adjust threshold value
thresh = np.max(laplacian)/4
laplacian[laplacian < thresh] = 0
laplacian[laplacian >= thresh] = 255
 
# Show the edges of image
plt.imshow(laplacian, cmap="gray")
plt.title('Laplacian edge detection')
plt.show()     

    The following is the code of visualizing the output of above edge detection methods.

 
# Collect all methods
edges = {"Original": img, "Canny edge": canny,
         "Sobel edge": sobel, "Laplacian edge": laplacian}

# display in a graph 
plt.subplots_adjust(wspace=.2, hspace=.2)
plt.tight_layout()

for i, (key, value) in enumerate(edges.items()):
    plt.subplot(2, 2, i + 1)
    plt.tick_params(labelbottom=False)
    plt.tick_params(labelleft=False)
    plt.title("{}".format(key))
    plt.imshow(value, cmap="gray")

plt.show()

    In this tutorial, we've briefly learned how to perform edge detection with OpenCV in Python. The full source code is listed below. 

 
Source code listing
 
  
import cv2
from matplotlib import pyplot as plt
import numpy as np  
 

file = "/Users/user/Desktop/sign.jpg" 
 
# Load an image
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
 
plt.imshow(img)
plt.show() 
 
# Apply Gaussian blur to remove noise img_blur = cv2.GaussianBlur(img, (3, 3), 0 
 
# Apply Sobel edge detection in the x and y directions
sobelx = cv2.Sobel(img_blur, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(img_blur, cv2.CV_64F, 0, 1, ksize=3)

# Combine the two gradients to produce an edge map
sobel = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0) 
   
plt.imshow(sobel, cmap='gray')
plt.title('Sobel edge detection')
plt.show() 
 
# Apply Canny edge detection 
canny = cv2.Canny(img_blur, 100, 200)

# display the image
plt.imshow(canny)
plt.title('Canny edge detection')
plt.show()  
 
# Apply Laplacian edge detection
laplacian = cv2.Laplacian(img_blur, cv2.CV_64F)

# Threshold the edge map, adjust threshold value
thresh = np.max(laplacian)/4
laplacian[laplacian < thresh] = 0
laplacian[laplacian >= thresh] = 255 
 
# Show the edges of image
plt.imshow(laplacian, cmap="gray")
plt.title('Laplacian edge detection')
plt.show() 
 
# Collect all methods
edges = {"Original": img, "Canny": canny,
         "Sobel": sobel, "Laplacian": laplacian}

# display in a graph 
plt.subplots_adjust(wspace=.2, hspace=.2)
plt.tight_layout()

for i, (key, value) in enumerate(edges.items()):
    plt.subplot(2, 2, i + 1)
    plt.tick_params(labelbottom=False)
    plt.tick_params(labelleft=False)
    plt.title("{} edge".format(key))
    plt.imshow(value, cmap="gray")

plt.show()     
  
 
 


No comments:

Post a Comment