python opncv Canny边缘检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TingHW/article/details/84527500
# Canny 边缘检测是一个多步骤的算法。


# Canny边缘检测: 
# OpenCV-Python中Canny函数的原型为: 
# edge = cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient ]]]) 
 
# 必要参数: 
# 第一个参数是需要处理的原图像,该图像必须为单通道的灰度图; 
# 第二个参数是阈值1; 
# 第三个参数是阈值2。 
 
# 其中较大的阈值2用于检测图像中明显的边缘,但一般情况下检测的效果不会那么完美 
# ,边缘检测出来是断断续续的。所以这时候用较小的第一个阈 
# 值用于将这些间断的边缘连接起来。 
 
# 可选参数中apertureSize就是Sobel算子的大小。而L2gradient参数是一个布尔值, 
# 如果为真,则使用更精确的L2范数进行计算(即两个方向的倒数的平方和再开放) 
# ,否则使用L1范数(直接将两个方向导数的绝对值相加)。 
 
# 函数返回一副二值图,其中包含检测出的边缘。 
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('touxiang.jpg',0)
# img=cv2.GaussianBlur(img,(3,3),0) 
edges = cv2.Canny(img,100,250)

cv2.imshow('edges',edges)
cv2.waitKey(0)
cv2.destroyAllWindows()


''''' 
Canny边缘检测:优化的程序 带进度条的
'''  
import cv2  
import numpy as np   
  
def CannyThreshold(lowThreshold):    
    detected_edges = cv2.GaussianBlur(gray,(3,3),0) #高斯滤波   
    detected_edges = cv2.Canny(detected_edges,  
            lowThreshold,  
            lowThreshold*ratio,  
            apertureSize = kernel_size)  #边缘检测  
  
     # just add some colours to edges from original image.    
    dst = cv2.bitwise_and(img,img,mask = detected_edges)  #用原始颜色添加到检测的边缘上  
    cv2.imshow('canny demo',dst)    
    
  
lowThreshold = 0    
max_lowThreshold = 100    
ratio = 3    
kernel_size = 3    
    
img = cv2.imread('touxiang.jpg')    
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  #转换彩色图像为灰度图  
    
cv2.namedWindow('canny demo')    
    
#设置调节杠,  
''''' 
下面是第二个函数,cv2.createTrackbar() 
 
共有5个参数,其实这五个参数看变量名就大概能知道是什么意思了 
 
第一个参数,是这个trackbar对象的名字 
 
第二个参数,是这个trackbar对象所在面板的名字 
 
第三个参数,是这个trackbar的默认值,也是调节的对象 
 
第四个参数,是这个trackbar上调节的范围(0~count) 
 
第五个参数,是调节trackbar时调用的回调函数名 
'''  
cv2.createTrackbar('Min threshold','canny demo',lowThreshold, max_lowThreshold, CannyThreshold)    
    
CannyThreshold(0)  # initialization    
if cv2.waitKey(0) == 27:  #wait for ESC key to exit cv2  
    cv2.destroyAllWindows()    

猜你喜欢

转载自blog.csdn.net/TingHW/article/details/84527500
今日推荐