由于一共8张图(1个原图+7个边缘检测效果图),所以分别放在2个2×2的图中,这样的显示的图不至于太小(一开始放在2×4的图中,但是显示太小了,看不出边缘检测的效果如何)。
结论:Scharr算子的边缘检测效果更好 (有个疑问,效果图是否和图片有关系???后续再研究一下)
代码如下:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取本地图片
img=cv2.imread('D:/picture/right_2.jpg')
# opencv是用的BGR格式,后面用plt输出,要转换成RGB格式,因为matplotlib用的RGB格式
image=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
GRAYimage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 灰度化处理图像
gaussian=cv2.GaussianBlur(GRAYimage,(3,3),0)# 高斯滤波降噪
#Roberts
kernelx=np.array([[-1,0],[0,1]],dtype=int)
kernely=np.array([[0,-1],[1,0]],dtype=int)
x=cv2.filter2D(GRAYimage,cv2.CV_16S,kernelx)
y=cv2.filter2D(GRAYimage,cv2.CV_16S,kernely)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Roberts=cv2.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=cv2.filter2D(GRAYimage,cv2.CV_16S,kernelx)
y=cv2.filter2D(GRAYimage,cv2.CV_16S,kernely)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Prewitt=cv2.addWeighted(absX,0.5,absY,0.5,0)
#Sobel
x=cv2.Sobel(GRAYimage,cv2.CV_16S,1,0)
y=cv2.Sobel(GRAYimage,cv2.CV_16S,0,1)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Sobel=cv2.addWeighted(absX,0.5,absY,0.5,0)
#Lapacian
dst=cv2.Laplacian(GRAYimage,cv2.CV_16S,ksize=3)
Laplacian=cv2.convertScaleAbs(dst)
#Scharr
x=cv2.Scharr(GRAYimage,cv2.CV_32F,1,0)
y=cv2.Scharr(GRAYimage,cv2.CV_32F,0,1)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Scharr=cv2.addWeighted(absX,0.5,absY,0.5,0)
#Canny
Canny=cv2.Canny(gaussian,50,150)
#log
dst=cv2.Laplacian(gaussian,cv2.CV_16S,ksize=3)
LOG=cv2.convertScaleAbs(dst)
titles = ['origin image','Canny image','LOG image','Roberts image']
images = [image,Canny,LOG,Roberts]
for i in range(4):
plt.subplot(2,2,i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
titles = ['Prewitt image','Sobel image','Laplacian image','Scharr image']
images = [Prewitt,Sobel,Laplacian,Scharr]
for i in range(4):
plt.subplot(2,2,i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])