标签:shadow 函数 创建 abs scale ext har pre show
简述OpenCV边缘检测的一般步骤为:
常用的边缘检测的算子和滤波器有:
以下使用Sobel、Laplacian和Canny算子进行边缘检测。图片是从网上随意下载的一张。
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()
OpenCV实战(一): Sobel、Laplacian、Canny 边缘检测
标签:shadow 函数 创建 abs scale ext har pre show
原文地址:http://blog.51cto.com/weiyuqingcheng/2335243