import cv2
import numpy as np
def roberts_edge_extraction(image, border_width):
# Convert the image to float32
image = image.astype(np.float32)
# Apply Roberts edge detection
roberts_x = cv2.filter2D(image, -1, np.array([[1, 0], [0, -1]], dtype=np.float32))
roberts_y = cv2.filter2D(image, -1, np.array([[0, 1], [-1, 0]], dtype=np.float32))
# Calculate the gradient magnitude
gradient_magnitude = np.sqrt(roberts_x**2 + roberts_y**2)
# Threshold the gradient magnitude to obtain the edges
threshold = np.max(gradient_magnitude) * 0.1 # Adjust the threshold value as needed
edges = np.where(gradient_magnitude > threshold, 255, 0).astype(np.uint8)
# Dilate the edges to increase the width
kernel = np.ones((border_width, border_width), np.uint8)
dilated_edges = cv2.dilate(edges, kernel, iterations=1)
return dilated_edges
# Load a grayscale image
image = cv2.imread('your_image.jpg', cv2.IMREAD_GRAYSCALE)
# Apply Roberts edge extraction with a border width of 3 pixels
border_width = 3
edges = roberts_edge_extraction(image, border_width)
# Display the original image and the edges
cv2.imshow('Original Image', image)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
使用opencv提取灰度图的边界
最新推荐文章于 2024-04-24 20:18:45 发布