OpenCV邊緣檢測的通常步驟爲:ide
經常使用的邊緣檢測的算子和濾波器有:函數
如下使用Sobel、Laplacian和Canny算子進行邊緣檢測。圖片是從網上隨意下載的一張。code
import cv2 #********************Sobel邊緣檢測***************************** def edge_sobel( src ): kernelSize = (3, 3) gausBlurImg = cv2.GaussianBlur( src, kernelSize, 0 ) #轉換爲灰度圖 channels = src.shape[2] if channels > 1: src_gray = cv2.cvtColor( gausBlurImg, cv2.COLOR_RGB2GRAY ) else: src_gray = src.clone() scale = 1 delta = 0 depth = cv2.CV_16S #求X方向梯度(建立grad_x, grad_y矩陣) grad_x = cv2.Sobel( src_gray, depth, 1, 0 ) abs_grad_x = cv2.convertScaleAbs( grad_x ) #求Y方向梯度 grad_y = cv2.Sobel( src_gray, depth, 0, 1 ) abs_grad_y = cv2.convertScaleAbs( grad_y ) #合併梯度(近似) edgeImg = cv2.addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0 ) return edgeImg #********************Laplacian邊緣檢測***************************** def edge_laplacian( src ): scale = 1 delta = 0 depth = cv2.CV_16S if src.shape[2] > 1: src_gray = cv2.cvtColor( src, cv2.COLOR_RGB2GRAY ) else: src_gray = src.clone() kernelSize = (3, 3) gausBlurImg = cv2.GaussianBlur( src_gray, kernelSize, 0 ) laplacianImg = cv2.Laplacian( gausBlurImg, depth, kernelSize ) edgeImg = cv2.convertScaleAbs( laplacianImg ) return edgeImg #********************Canny邊緣檢測***************************** def edge_canny( src, threshold1, threshold2 ): kernelSize = (3, 3) gausBlurImg = cv2.GaussianBlur( src, kernelSize, 0 ) edgeImg = cv2.Canny( gausBlurImg, threshold1, threshold2 ) return edgeImg #********************主函數***************************** imgSrc = cv2.imread( "1.jpg" ) sobelImg = edge_sobel( imgSrc ) laplacianImg = edge_laplacian( imgSrc ) cannyImg = edge_canny( imgSrc, 20, 60 ) cv2.imshow( "Origin", imgSrc ) cv2.imshow( "Sobel", sobelImg ) cv2.imshow( "Laplacian", laplacianImg ) cv2.imshow( "Canny", cannyImg ) cv2.waitKey( 0 ) cv2.destroyAllWindows()