You can download this code by clicking the button below.
This code is now available for download.
This function performs edge detection. It first loads the image, then converts it to grayscale, and applies the Canny edge detection algorithm. Optionally, it can apply non-maximum suppression and Hough transform to detect lines in the image.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def edge_detection(image_path, threshold=100, non_max_suppression=True):
import cv2
import numpy as np
# Load the image
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Canny edge detection
edges = cv2.Canny(gray, threshold, threshold * 2, apertureSize=3, L2gradient=True)
# Optionally apply non-maximum suppression
if non_max_suppression:
edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
linesP = cv2.HoughLinesP(edges, 1, np.pi/180, threshold, None, minLineLength=100, maxLineGap=10)
if linesP is not None:
for line in linesP:
x1, y1, x2, y2 = line[0]
cv2.line(edges, (x1, y1), (x2, y2), (255, 0, 0), 2)
return edges