import cv2 as cv

if __name__ == '__main__':
    img = cv.imread("lena.png", flags=1)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    SobelX = cv.Sobel(imgGray, cv.CV_16S, 1, 0)  # 计算 x 轴方向
    SobelY = cv.Sobel(imgGray, cv.CV_16S, 0, 1)  # 计算 y 轴方向
    absX = cv.convertScaleAbs(SobelX)  # 转回 uint8
    absY = cv.convertScaleAbs(SobelY)  # 转回 uint8
    SobelXY = cv.addWeighted(absX, 0.5, absY, 0.5, 0)  # 用绝对值近似平方根

    cv.imshow("Sobel gradient", SobelXY)
    cv.waitKey(0)