Sobel Operator:
import cv2
import numpy as np
# Read the input image
image = cv2.imread('C://Users//HP//OneDrive//Desktop//Anna//Ramu.jpg',cv2.IMREAD_GRAYSCALE)
# Apply Sobel operator in x and y directions
sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) # Sobel operator in x direction
sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3) # Sobel operator in y direction
# Combine the results to get the final edge-detected image
sobel_combined = cv2.sqrt(cv2.add(cv2.pow(sobelx, 2), cv2.pow(sobely, 2)))
# Convert the result to the appropriate data type for visualization
sobel_combined = np.uint8(sobel_combined)
# Display the original and edge-detected images
cv2.imshow('Original Image', image)
cv2.imshow('Sobel Edge Detection', sobel_combined)
cv2.waitKey(0)
cv2.destroyAllWindows()
Prewitt Operator:
import cv2
import numpy as np
def prewitt_operator(image):
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Prewitt kernels for horizontal and vertical edge detection
kernel_x = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
kernel_y = np.array([[-1, -1, -1],
[ 0, 0, 0],
[ 1, 1, 1]])
# Convolve the image with the kernels
gradient_x = cv2.filter2D(gray_image, -1, kernel_x)
gradient_y = cv2.filter2D(gray_image, -1, kernel_y)
# Compute the magnitude of the gradients
magnitude = np.sqrt(np.square(gradient_x) + np.square(gradient_y))
# Normalize the magnitude to the range [0, 255]
magnitude *= 255.0 / np.max(magnitude)
magnitude = magnitude.astype(np.uint8)
return magnitude
# Load an image
image = cv2.imread('C://Users//HP//OneDrive//Desktop//Anna//Ramu.jpg')
# Apply the Prewitt operator
edges = prewitt_operator(image)
# Display the original and edge-detected images
cv2.imshow('Original Image', image)
cv2.imshow('Prewitt Edge Detection', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Canny Edge Detector:
import cv2
# Load the image
image = cv2.imread('C://Users//HP//OneDrive//Desktop//Anna//Ramu.jpg', cv2.IMREAD_GRAYSCALE)
# Apply Canny edge detection
edges = cv2.Canny(image, 100, 200) # Adjust the thresholds as needed
# Display the original and Canny edge detected images
cv2.imshow('Original', image)
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Laplacian Operator:
import cv2
import numpy as np
# Load the image
image = cv2.imread('C://Users//HP//OneDrive//Desktop//Anna//Ramu.jpg', cv2.IMREAD_GRAYSCALE)
# Apply Laplacian operator
laplacian = cv2.Laplacian(image, cv2.CV_64F)
# Convert the result to uint8
laplacian_uint8 = np.uint8(np.absolute(laplacian))
# Display the original and Laplacian filtered images
cv2.imshow('Original', image)
cv2.imshow('Laplacian', laplacian_uint8)
cv2.waitKey(0)
cv2.destroyAllWindows()