import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Sobel算子
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
# 卷积操作
img_x = cv2.filter2D(gray, -1, sobel_x)
img_y = cv2.filter2D(gray, -1, sobel_y)
# 合并x和y方向的结果
grad = cv2.addWeighted(img_x, 0.5, img_y, 0.5, 0)
# 显示结果
cv2.imshow('Input', img)
cv2.imshow('Sobel', grad)
cv2.waitKey(0)
cv2.destroyAllWindows()
sobel算子代码
最新推荐文章于 2024-06-11 16:41:22 发布