# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#讀取圖像
img = cv.imread('d:/paojie.png')
img1 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
#灰度化處理圖像
grayImage = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#高斯濾波
gaussianBlur = cv.GaussianBlur(grayImage, (3,3), 0)
#閾值處理
ret, binary = cv.threshold(gaussianBlur, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
#Roberts算子
kernelx = np.array([[-1,0],[0,1]], dtype=int)
kernely = np.array([[0,-1],[1,0]], dtype=int)
x = cv.filter2D(binary, cv.CV_16S, kernelx)
y = cv.filter2D(binary, cv.CV_16S, kernely)
absX = cv.convertScaleAbs(x)
absY = cv.convertScaleAbs(y)
Roberts = cv.addWeighted(absX, 0.5, absY, 0.5, 0)
#Prewitt算子
kernelx = np.array([[1,1,1],[0,0,0],[-1,-1,-1]], dtype=int)
kernely = np.array([[-1,0,1],[-1,0,1],[-1,0,1]], dtype=int)
x = cv.filter2D(binary, cv.CV_16S, kernelx)
y = cv.filter2D(binary, cv.CV_16S, kernely)
absX = cv.convertScaleAbs(x)
absY = cv.convertScaleAbs(y)
Prewitt = cv.addWeighted(absX,0.5,absY,0.5,0)
#Sobel算子
x = cv.Sobel(binary, cv.CV_16S, 1, 0)
y = cv.Sobel(binary, cv.CV_16S, 0, 1)
absX = cv.convertScaleAbs(x)
absY = cv.convertScaleAbs(y)
Sobel = cv.addWeighted(absX, 0.5, absY, 0.5, 0)
#拉普拉斯算法
dst = cv.Laplacian(binary, cv.CV_16S, ksize = 3)
Laplacian = cv.convertScaleAbs(dst)
#效果圖
titles = ['Source Image', 'Binary Image', 'Roberts Image',
'Prewitt Image','Sobel Image', 'Laplacian Image']
images = [img1, binary, Roberts, Prewitt, Sobel, Laplacian]
for i in np.arange(6):
plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
輸出結(jié)果如圖所示晴裹。其中瘾敢,Laplacian算子對(duì)噪聲比較敏感田盈,由于其算法可能會(huì)出現(xiàn)雙像素邊界畜号,常用來(lái)判斷邊緣像素位于圖像的明區(qū)或暗區(qū),很少用于邊緣檢測(cè)允瞧;Robert算子對(duì)陡峭的低噪聲圖像效果較好简软,尤其是邊緣正負(fù)45度較多的圖像蛮拔,但定位準(zhǔn)確率較差;Prewitt算子對(duì)灰度漸變的圖像邊緣提取效果較好替饿,而沒(méi)有考慮相鄰點(diǎn)的距離遠(yuǎn)近對(duì)當(dāng)前像素點(diǎn)的影響语泽;Sobel算子考慮了綜合因素,對(duì)噪聲較多的圖像處理效果更好视卢。
表示各種邊緣檢測(cè)算子