sobel,canny(可滑动调节阈值)边缘检测算法opencv-python实战

1.前言

目的:为了总结下之前用过的经典边缘检测算法sobel和canny

2.算法opencv官方讲解

(1)sobel
算法讲解
(2)canny
算法讲解

2.opencv-python代码

**注意:**由于数据未公开,所以没有提供数据来源,只需要填写path(图像的路径)即可运行,该代码可以实现以上两种算法,并且canny算法的阈值是可以通过滑动块来设置的。代码已有详细的注释。

import cv2

# original image
path =''
original_image = cv2.imread(path, 1)
cv2.imshow('original image', original_image)
cv2.waitKey()

# edge detection by sobel
gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)  # 彩色也可以处理,但是最好是灰度图
cv2.imshow('gray_image', gray_image)
cv2.waitKey()
x = cv2.Sobel(gray_image, cv2.CV_16S, 1, 0)  # 对x求一阶导,垂直检测,一个图像左顶点才是圆点,垂直向下为x轴,水平向右为y轴
y = cv2.Sobel(gray_image, cv2.CV_16S, 0, 1)  # 对y求一阶导,水平检测
absX = cv2.convertScaleAbs(x)  # 实现将x转换为uint8类型,因为x会有正有负,转换到[0,255]
absY = cv2.convertScaleAbs(y)
cv2.imshow('absX', absX)
cv2.waitKey()
cv2.imshow('absY', absY)
cv2.waitKey()
sobel_image = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
cv2.imshow('sobel_image', sobel_image)
cv2.waitKey()

# edge detection by canny with dynamic thresholds
gaussian_image = cv2.GaussianBlur(gray_image, (3, 3), 0)  # 高斯核的长宽都是的正奇数, 高斯模糊会使图像模糊,但会滤除高斯类噪点
cv2.imshow('gaussian_image', gaussian_image)
cv2.waitKey()

def nothing(x):  # 每次滑动bar的时候,不需要额外的回调
    pass
cv2.namedWindow('canny with dynamic thresholds')  # 给窗口命名
cv2.createTrackbar('min', 'canny with dynamic thresholds', 0, 255, nothing)  # 这里第二个参数必须是当前的窗口名,范围[0,255]
cv2.createTrackbar('max', 'canny with dynamic thresholds', 0, 255, nothing)
while(1):
    if cv2.waitKey(1) & 0xFF == 27:  # ESC退出循环,关闭所有的窗口哦
        break
    maxVal = cv2.getTrackbarPos('max', 'canny with dynamic thresholds')
    minVal = cv2.getTrackbarPos('min', 'canny with dynamic thresholds')
    canny_image = cv2.Canny(gaussian_image, minVal, maxVal)  # 范围[0,25*10.2]=[0,255]
    cv2.imshow('canny_image', canny_image)

cv2.destroyAllWindows()

你可能感兴趣的:(deep,learning)