圖像梯度
梯度簡單來說就是求導(dǎo)。
OpenCV 提供了三種不同的梯度濾波器血淌,或者說高通濾波器:Sobel,Scharr 和 Laplacian晚顷。Sobel,Scharr 其實(shí)就是求一階或二階導(dǎo)數(shù)瞳氓。Scharr 是對 Sobel(使用小的卷積核求解求解梯度角度時(shí))的優(yōu)化栓袖。Laplacian 是求二階導(dǎo)數(shù)。
Sobel 算子是一個(gè)主要用作邊緣檢測的離散微分算子 (discrete differentiation operator)音榜。 Sobel算子結(jié)合了高斯平滑和微分求導(dǎo)捧弃,用來計(jì)算圖像灰度函數(shù)的近似梯度。在圖像的任何一點(diǎn)使用此算子嘴办,將會(huì)產(chǎn)生對應(yīng)的梯度矢量或是其法矢量买鸽。
cv2.Sobel(src,cv2.ddepth,dx,dy,Ksize)
參數(shù)意義如下:
- src:輸入圖像
- ddepth:輸出圖像的深度,支持如下src.depth()和ddepth的組合:
- 若src.depth() = CV_8U, 取ddepth =-1/CV_16S/CV_32F/CV_64F
- 若src.depth() = CV_16U/CV_16S, 取ddepth =-1/CV_32F/CV_64F
- 若src.depth() = CV_32F, 取ddepth =-1/CV_32F/CV_64F
- 若src.depth() = CV_64F, 取ddepth = -1/CV_64F
- dx:x 方向上的差分階數(shù)
- dy:y方向上的差分階數(shù)
- ksize:核大小,默認(rèn)值3妆艘,表示Sobel核的大小; 必須取1看幼,3,5或7朱沃;
例子:sobel
def img_show(name,image):
"""matplotlib圖像顯示函數(shù)
name:字符串茅诱,圖像標(biāo)題
img:numpy.ndarray,圖像
"""
if len(image.shape) == 3:
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
plt.imshow(image,'gray')
plt.xticks([])
plt.yticks([])
plt.xlabel(name,fontproperties='FangSong',fontsize=12)
if __name__=="__main__":
img = cv2.imread('data/building.jpg',0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
#cv2.CV_64F輸出圖像的深度(數(shù)據(jù)類型)翎卓,可以使用-1,與原圖像保持一致np.uint8
#參數(shù)1,0為只在x方向求一階導(dǎo)數(shù)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
#參數(shù)0,1為只在y方向求一階導(dǎo)數(shù)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
#sobel =cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3) # 效果不好
sobel = cv2.add(sobelx,sobely)
plt.figure(figsize=(10,8),dpi=80)
plt.subplot(221)
img_show('原圖',img)
plt.subplot(222)
img_show('sobelx',sobelx)
plt.subplot(223)
img_show('sobely',sobely)
plt.subplot(224)
img_show('sobel',sobel)
例子:scharr
def img_show(name,image):
"""matplotlib圖像顯示函數(shù)
name:字符串坯门,圖像標(biāo)題
img:numpy.ndarray逗扒,圖像
"""
if len(image.shape) == 3:
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
plt.imshow(image,'gray')
plt.xticks([])
plt.yticks([])
plt.xlabel(name,fontproperties='FangSong',fontsize=12)
if __name__=="__main__":
img = cv2.imread('data/building.jpg',0)
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharr = cv2.add(scharrx,scharry)
plt.figure(figsize=(10,8),dpi=80)
plt.subplot(221)
img_show('原圖',img)
plt.subplot(222)
img_show('scharrx',scharrx)
plt.subplot(223)
img_show('scharry',scharry)
plt.subplot(224)
img_show('scharr',scharr)
例子:laplacian
def img_show(name,image):
"""matplotlib圖像顯示函數(shù)
name:字符串矩肩,圖像標(biāo)題
img:numpy.ndarray,圖像
"""
if len(image.shape) == 3:
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
plt.imshow(image,'gray')
plt.xticks([])
plt.yticks([])
plt.xlabel(name,fontproperties='FangSong',fontsize=12)
if __name__=="__main__":
img = cv2.imread('data/building.jpg',0)
laplacian = cv2.Laplacian(img,cv2.CV_64F,ksize=5)
plt.figure(figsize=(10,8),dpi=80)
plt.subplot(121)
img_show('原圖',img)
plt.subplot(122)
img_show('laplacian',laplacian)
參考資料
《數(shù)字圖像處理》《OpenCV-Python-Toturial-中文版》