用python写sobel算子
时间: 2023-06-08 10:05:46 浏览: 108
好的,我可以为您提供用Python写Sobel算子的代码。以下是一些示例代码:
```
import cv2
import numpy as np
def sobel(img, threshold):
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Sobel operators for x and y
sobelx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobely = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
# Convolve the image with the Sobel operators
grad_x = cv2.filter2D(gray, cv2.CV_16S, sobelx)
grad_y = cv2.filter2D(gray, cv2.CV_16S, sobely)
# Convert back to 8-bit integers
abs_grad_x = cv2.convertScaleAbs(grad_x)
abs_grad_y = cv2.convertScaleAbs(grad_y)
# Calculate the gradient magnitude
grad_mag = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
# Use threshold to find edges
edges = cv2.threshold(grad_mag, threshold, 255, cv2.THRESH_BINARY)[1]
return edges
# Load image
img = cv2.imread('image.jpg')
# Apply Sobel operator
edges = sobel(img, 100)
# Display results
cv2.imshow('Original', img)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,以上代码需要使用OpenCV库。将图像传递给`sobel()`函数以应用Sobel算子,并传递一个阈值参数以找到边缘。这将返回一幅图像,其中仅包含边缘。