0
0
Computer Visionml~5 mins

Image gradients (Sobel, Laplacian) in Computer Vision

Choose your learning style9 modes available
Introduction

Image gradients help us find edges and shapes in pictures by showing where colors change quickly.

To detect edges in photos for object recognition.
To highlight boundaries in medical images like X-rays.
To prepare images for further analysis like shape detection.
To improve photo filters that rely on edges.
To find motion or changes between video frames.
Syntax
Computer Vision
import cv2

# Load image in grayscale
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Sobel gradient
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)

# Laplacian gradient
laplacian = cv2.Laplacian(image, cv2.CV_64F)

Sobel calculates gradients in horizontal (x) and vertical (y) directions separately.

Laplacian calculates the second derivative, showing where intensity changes rapidly in all directions.

Examples
Calculates vertical edges by looking at changes left to right.
Computer Vision
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
Calculates horizontal edges by looking at changes top to bottom.
Computer Vision
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
Finds edges by combining changes in all directions.
Computer Vision
laplacian = cv2.Laplacian(image, cv2.CV_64F)
Sample Model

This code creates a simple image with a white square on black background. It then calculates the Sobel gradients in x and y directions and the Laplacian gradient. Finally, it prints the total edge strength detected by each method.

Computer Vision
import cv2
import numpy as np

# Create a simple black image with a white square
image = np.zeros((100, 100), dtype=np.uint8)
cv2.rectangle(image, (30, 30), (70, 70), 255, -1)

# Calculate Sobel gradients
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)

# Calculate Laplacian gradient
laplacian = cv2.Laplacian(image, cv2.CV_64F)

# Convert gradients to absolute values and 8-bit for display
abs_sobel_x = cv2.convertScaleAbs(sobel_x)
abs_sobel_y = cv2.convertScaleAbs(sobel_y)
abs_laplacian = cv2.convertScaleAbs(laplacian)

# Print sum of gradient values to show edge strength
print(f"Sum of Sobel X edges: {np.sum(abs_sobel_x)}")
print(f"Sum of Sobel Y edges: {np.sum(abs_sobel_y)}")
print(f"Sum of Laplacian edges: {np.sum(abs_laplacian)}")
OutputSuccess
Important Notes

Sobel gradients are good for detecting edges in specific directions.

Laplacian is more sensitive and detects edges in all directions but can be noisier.

Always convert gradients to absolute values before displaying or analyzing.

Summary

Image gradients highlight edges by showing where pixel brightness changes quickly.

Sobel finds edges horizontally and vertically, while Laplacian finds edges in all directions.

These techniques help computers understand shapes and objects in images.