上一篇《OpenCV入門第二篇》縮放圖像介紹瞭如何對圖像大小進行縮放。這篇講解如何對圖像邊緣進行檢測提取,圖像的邊緣檢測的原理是檢測出圖像中所有灰度值變化較大的點,而且這些點連接起來就構成了若干線條,這些線條就可以稱爲圖像的邊緣。Canny邊緣檢測算子是John F. Canny於 1986 年開發出來的一個多級邊緣檢測算法。
函數介紹
高斯模糊GaussianBlur函數
GaussianBlur(
src, 輸入圖像
ksize, 高斯內核大小(正奇數)
sigmaX, 在X方向上的標準差
dst, 目標圖像
sigmaY, 在Y方向上的標準差
borderType 邊界類型參數
)
顏色空間轉換cvtColor函數
cvtColor(
src, 原圖像
code, 轉換代碼標識
dst, 輸出圖像
dstCn 目標圖像的通道數
)
邊緣提取Canny函數
Canny(
image, 輸入原圖
threshod1, 檢測邊緣的低閾值
threshod2, 檢測邊緣的高閾值
edges, 表示輸出邊緣圖像
apertureSize, Sobel算子的大小
L2gradient 使用範數參數true爲L2範數,false爲L1範數
)
圖像基本與運算bitwise_and函數
cv2.bitwise_and(
src1, 圖像1
src2, 圖像2
dst, 目標圖像
mask 掩膜(用選定的圖像、圖形或物體,對處理的圖像(全部或局部)進行遮擋,來控制圖像處理的區域或處理過程)
)
示例代碼
import cv2
#canny邊緣提取函數
def get_edge(image):
#高斯模糊函數:GaussianBlur(src,ksize,sigmaX,dst,sigmaY,borderType)src爲輸入圖像,
#dst爲目標圖像,ksize表示高斯內核大小(正奇數),sigmaX和sigmaY分別表示在X、Y方向上的標準差。
image_blur = cv2.GaussianBlur(image, (3, 3), 0)
#顏色空間轉換函數:cvtColor(src,code,dst,dstCn)src爲原圖像,code爲轉換代碼標識,
#dst爲輸出圖像,dstCn是目標圖像的通道數。
image_gray = cv2.cvtColor(image_blur, cv2.COLOR_RGB2GRAY)
#Canny邊緣提取:Canny(image,threshod1,threshod2,edges,apertureSize,L2gradient)
#image爲輸入原圖,threshod1、threshod2分別是檢測邊緣的低、高閾值,apertureSize是Sobel算子
#的大小,L2gradient使用範數參數,true爲L2範數,false爲L1範數。
image_edge = cv2.Canny(image_gray, 50, 150)
cv2.imshow("Canny Edge", image_edge)
#圖像基本運算:bitwise_and是二進制與運算,bitwise_or是二進制或運算等等。
cv2.bit
color_edge = cv2.bitwise_and(image, image, mask= image_edge)
cv2.imshow("Color Edge", color_edge)
#讀取一張圖片並對其進行canny邊緣提取
image = cv2.imread("E:\MyQQFile\Photos\\baby4_half.jpg")
#展示圖片
cv2.namedWindow("Input_Image",cv2.WINDOW_AUTOSIZE)
cv2.imshow("Input_Image",image)
get_edge(image)
cv2.waitKey(0)
cv2.destroyAllWindows()