OpenCV—python 邊緣檢測(Canny)
阿新 • • 發佈:2018-12-13
一、OpenCV-Python 中 Canny() 引數
"""
cv2.Canny(image, # 輸入原圖(必須為單通道圖)
threshold1,
threshold2, # 較大的閾值2用於檢測影象中明顯的邊緣
[, edges[,
apertureSize[, # apertureSize:Sobel運算元的大小
L2gradient ]]]) # 引數(布林值):
true: 使用更精確的L2範數進行計算(即兩個方向的倒數的平方和再開放),
false:使用L1範數(直接將兩個方向導數的絕對值相加)。
"""
import cv2
import numpy as np
original_img = cv2.imread("qingwen.png", 0)
# canny(): 邊緣檢測
img1 = cv2.GaussianBlur(original_img,(3,3),0)
canny = cv2.Canny(img1, 50, 150)
# 形態學:邊緣檢測
_,Thr_img = cv2.threshold(original_img,210,255,cv2.THRESH_BINARY)#設定紅色通道閾值210(閾值影響梯度運算效果)
kernel = cv2.getStructuringElement( cv2.MORPH_RECT,(5,5)) #定義矩形結構元素
gradient = cv2.morphologyEx(Thr_img, cv2.MORPH_GRADIENT, kernel) #梯度
cv2.imshow("original_img", original_img)
cv2.imshow("gradient", gradient)
cv2.imshow('Canny', canny)
cv2.waitKey(0)
cv2.destroyAllWindows()
可調整閾值大小的程式
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)
dst = cv2.bitwise_and(img,img,mask = detected_edges) # just add some colours to edges from original image.
cv2.imshow('canny demo',dst)
lowThreshold = 0
max_lowThreshold = 100
ratio = 3
kernel_size = 3
img = cv2.imread('qingwen.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.namedWindow('canny demo')
cv2.createTrackbar('Min threshold','canny demo',lowThreshold, max_lowThreshold, CannyThreshold)
CannyThreshold(0) # initialization
if cv2.waitKey(0) == 27:
cv2.destroyAllWindows()