Python+OpenCV入门教程【十一】图像梯度

图像梯度的基本原理:点击了解

下面展示 代码

import cv2 as cv

# 图像梯度:索贝尔算子
def sobel_image(image):
    grad_x = cv.Sobel(image, cv.CV_32F, 1, 0)  # x方向导数
    grad_y = cv.Sobel(image, cv.CV_32F, 0, 1)  # y方向导数
    gradx = cv.convertScaleAbs(grad_x)
    grady = cv.convertScaleAbs(grad_y)
    cv.imshow("x_direction", gradx)  # 颜色变化在水平分层
    cv.imshow("y_direction", grady)  # 颜色变化在垂直分层
    # 按权重合成两张图
    gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
    # 合成
    cv.imshow("composite", gradxy)

#图像梯度:scharr算子:增强边缘
def scharr_image(image):
    grad_x = cv.Scharr(image, cv.CV_32F, 1, 0)#x方向导数
    grad_y = cv.Scharr(image, cv.CV_32F, 0, 1)#y方向导数
    gradx = cv.convertScaleAbs(grad_x)
    grady = cv.convertScaleAbs(grad_y)
    cv.imshow("x_direction", gradx)#颜色变化在水平分层
    cv.imshow("y_direction", grady)#颜色变化在垂直分层
    gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
    cv.imshow("composite", gradxy)

#拉普拉斯算子
def lapalian_image(image):
    dst = cv.Laplacian(image, cv.CV_32F)
    lpls = cv.convertScaleAbs(dst)
    cv.imshow("lapalian", lpls)

if __name__ == '__main__':
    '''
    索贝尔算子sobel_image()
    '''
    # src = cv.imread("pic/cat.jpg")
    # cv.imshow("original", src)
    # sobel_image(src)
    # cv.waitKey(0)
    # cv.destroyAllWindows()

    '''
    scharr_image() 增强边缘
    '''
    # src = cv.imread("pic/cat.jpg")
    # cv.imshow("original", src)
    # scharr_image(src)
    # cv.waitKey(0)
    # cv.destroyAllWindows()

    '''
    拉普拉斯算子lapalian_image()
    '''
    src = cv.imread("pic/cat.jpg")
    cv.imshow("original", src)
    lapalian_image(src)
    cv.waitKey(0)
    cv.destroyAllWindows()

你可能感兴趣的:(python+openCV,opencv,cv,计算机视觉,经验分享)