python+openCV使用滑动条调节阈值进行Canny边缘检测

Canny边缘检测一般流程

  • 高斯滤波,平滑图像,减弱噪声
  • 计算图像梯度大小和方向
  • 非极大值抑制,稀疏边缘
  • 滞后阈值(双阈值检测)

函数cv2.Canny(image, threshold1, threshold2[, apertureSize[, L2gradient]])

参数:

  • image:深度为8位的图像
  • threshold1:滞后阈值中的低阈值
  • threshold2:滞后阈值中的高阈值
  • apertureSize:Sobel边缘检测中的卷积框大小
  • L2gradient:精度设置,默认为False

返回值

单通道且图像深度为8位的图像,即灰度图像

e.g.

设置两个滑动条,分别控制threshold1,threshold2

import cv2
#载入图片
img_original=cv2.imread('E:\ImagesFavour\\5.2.3.jpg')
#设置窗口
cv2.namedWindow('Canny')
#定义回调函数
def nothing(x):
    pass
#创建两个滑动条,分别控制threshold1,threshold2
cv2.createTrackbar('threshold1','Canny',50,400,nothing)
cv2.createTrackbar('threshold2','Canny',100,400,nothing)
while(1):
    #返回滑动条所在位置的值
    threshold1=cv2.getTrackbarPos('threshold1','Canny')
    threshold2=cv2.getTrackbarPos('threshold2','Canny')
    #Canny边缘检测
    img_edges=cv2.Canny(img_original,threshold1,threshold2)
    #显示图片
    cv2.imshow('original',img_original)
    cv2.imshow('Canny',img_edges)  
    if cv2.waitKey(1)==ord('q'):
        break
cv2.destroyAllWindows()

结果显示如下:

发布了29 篇原创文章 · 获赞 26 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42216109/article/details/89764082