Edge detection

Mehmet Akif Cifci
2 min readFeb 22, 2023

--

Edge detection is a common image processing task that involves identifying the boundaries between objects in an image. OpenCV is a popular computer vision library that provides a variety of tools for performing edge detection on images. Here is a simple example of how to perform edge detection in OpenCV using the Canny edge detection algorithm. Sample code.

import cv2
import numpy as np

# Load an image
img = cv2.imread('image.jpg', 0)

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

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

# Display the resulting image
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

In the above code, we first load an image using the cv2.imread() function. The second argument specifies the color space in which to load the image, and 0 indicates that we want to load the image in grayscale.

We then apply a Gaussian blur to the image using the cv2.GaussianBlur() function. This helps to reduce noise in the image and produce smoother edges.

Finally, we apply the Canny edge detection algorithm using the cv2.Canny() function. The two arguments passed to this function specify the minimum and maximum threshold values for detecting edges. Any edges with intensity gradients below the minimum threshold are discarded, while those above the maximum threshold are considered strong edges. Edges with gradients between these two values are considered weak edges and are only retained if they are connected to strong edges.

The resulting image is displayed using the cv2.imshow() function. The cv2.waitKey() function waits for a key press before closing the window, while cv2.destroyAllWindows() closes all windows opened by OpenCV.

Note that there are many other edge detection algorithms available in OpenCV, including Sobel, Scharr, and Laplacian. Each algorithm has its own strengths and weaknesses, and the choice of algorithm will depend on the specific application.

--

--

Mehmet Akif Cifci
Mehmet Akif Cifci

Written by Mehmet Akif Cifci

Mehmet Akif Cifci holds the position of associate professor in the field of computer science in Austria.

No responses yet