Image gradients help us find edges and shapes in pictures by showing where colors change quickly.
Image gradients (Sobel, Laplacian) in 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.
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 = cv2.Laplacian(image, cv2.CV_64F)
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.
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)}")
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.
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.