Python example code of sobel operator
时间: 2023-02-21 15:25:41 浏览: 47
下面是 Python 实现 Sobel 算子的示例代码:
```
import numpy as np
import cv2
def sobel_operator(image):
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 计算 x 方向的 Sobel 导数
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
abs_sobel_x = np.absolute(sobel_x)
scaled_sobel_x = np.uint8(255 * abs_sobel_x / np.max(abs_sobel_x))
# 计算 y 方向的 Sobel 导数
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
abs_sobel_y = np.absolute(sobel_y)
scaled_sobel_y = np.uint8(255 * abs_sobel_y / np.max(abs_sobel_y))
# 合并 x 和 y 方向的结果
sobel_combined = cv2.addWeighted(scaled_sobel_x, 0.5, scaled_sobel_y, 0.5, 0)
return sobel_combined
```
这个代码实现了 Sobel 算子,它可以计算图像的梯度并返回边缘检测的结果。