import cv2
import numpy as np
def sobel(img_src):
img_sobel_64x = cv2.Sobel(img_src, cv2.CV_64F, 1, 0) # 图像深度 64位浮点数 x方向一阶求导
img_sobel_64y = cv2.Sobel(img_src, cv2.CV_64F, 0, 1) # Gx Gy
img_sobel_x = cv2.convertScaleAbs(img_sobel_64x) # 先计算数组绝对值,后转化为8位无符号数
img_sobel_y = cv2.convertScaleAbs(img_sobel_64y)
img_sobel = cv2.addWeighted(img_sobel_x, 0.5, img_sobel_y, 0.5, 0) # 梯度图像计算 G 强度
# H, W, C = img_sobel.shape[0], img_sobel.shape[1], img_sobel.shape[2]
# **** 计算梯度方向 ****
img_sobel_xdst = img_sobel_x.flatten()
img_sobel_ydst = img_sobel_y.flatten()
img_sobel_angle_arr = np.arctan2(img_sobel_ydst, img_sobel_xdst) * 180 / np.pi
img_sobel_angle = img_sobel_angle_arr.reshape(H, W ,C)
cv2.imshow("img_sobel", img_sobel)
return img_sobel
if __name__ == "__main__" :
img_src = cv2.imread('D:/demo/1.jpg')
img_sobel = sobel(img_src)
print(img_sobel.shape) # 查看 img_sobel 的shape
cv2.imshow('demo', img_sobel)
histogram_demo(img_sobel) # 绘制直方图
cv2.waitKey(0)
cv2.destroyAllWindows()
sobel算子处理图像python代码实现(计算梯度以及梯度方向)
最新推荐文章于 2024-06-25 14:57:14 发布