所谓空间滤波就是在图像上做卷积核和图像的卷积处理。所谓卷积其实在二维空间上就是卷积核翻转180度之后,卷积核和对应图像区域内的像素相乘相加生成新的像素值。空间滤波可以分为平滑空间滤波和锐化两种。
平滑空间滤波主要有:
1、均值滤波
2、高斯低通滤波
3、中值滤波
img=cv2.cvtColor(cv2.imread("lena512color.tiff"),cv2.COLOR_BGR2RGB)
blur_img=cv2.blur(img, (7,7)) #均值滤波
median_blur_img= cv2.medianBlur(img, 7) #中值滤波
gaussian_blur_img=cv2.GaussianBlur(img, (7,7), 0) #高斯低通滤波
plt.subplot(1,4,1)
plt.title("orignal image")
plt.imshow(img)
plt.subplot(1,4,2)
plt.title("mean blur image")
plt.imshow(blur_img)
plt.subplot(1,4,3)
plt.title("median blur image")
plt.imshow(median_blur_img)
plt.subplot(1,4,4)
plt.title("gaussian blur image")
plt.imshow(img)
plt.show()
锐化滤波主要是检测计算图像梯度,主要存在两种梯度,一种是一阶微分,使用图像像素的一阶差分可以计算。一种是二阶微分,使用二阶差分计算。具体上,可以使用这些差分算子进行卷积运行获得梯度幅值,之后再与原图像相加,增强图像边缘表达,从而达到锐化的效果。计算图像一阶微分的算子主要有:
Prewitt:
水平方向: 竖直方向:
sobel 算子:
水平方向: 竖直方向:
二阶微分:
拉普拉斯算子:
二阶微分没有方向,而且受噪声影响很大,所以在使用二阶微分算子时一般都会先做平滑处理。在这里,我们一般使用高斯低通平滑,那么现在高斯平滑之后再计算二阶微分,可以变成直接对高斯函数做二阶微分,然后再进行卷积计算。
拉普拉斯算子可以用两种:
img = cv2.imread("lena512color.tiff",0)
prewitt_x=[
[1,1,1],
[0,0,0],
[-1,-1,-1]
]
prewitt_y=[
[-1,0,1],
[-1,0,1],
[-1,0,1]
]
prewitt_x_img = cv2.filter2D(img, -1, np.array(prewitt_x))
prewitt_y_img = cv2.filter2D(img, -1, np.array(prewitt_y))
sobel_x = [
[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]
]
sobel_y = [
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
]
sobel_x_img = cv2.filter2D(img, -1, np.array(sobel_x))
sobel_y_img = cv2.filter2D(img, -1, np.array(sobel_y))
laplace_1=[
[0,-1,0],
[-1,4,-1],
[0,-1,0]
]
laplace_2 = [
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
]
laplace_1_img = cv2.filter2D(img, -1, np.array(sobel_x))
laplace_2_img = cv2.filter2D(img, -1, np.array(sobel_y))
plt.subplot(3,3,1)
plt.title("oringal image",fontdict={'weight':'normal','size': 5})
plt.imshow(img,cmap="gray")
plt.subplot(3,3,2)
plt.title("prewitt x image",fontdict={'weight':'normal','size': 5})
plt.imshow(prewitt_x_img)
plt.subplot(3,3,3)
plt.title("prewitt y image",fontdict={'weight':'normal','size': 5})
plt.imshow(prewitt_y_img)
plt.subplot(3,3,4)
plt.title("oringal image",fontdict={'weight':'normal','size': 5})
plt.imshow(img,cmap="gray")
plt.subplot(3, 3, 5)
plt.title("sobel x image",fontdict={'weight':'normal','size': 5})
plt.imshow(sobel_x_img)
plt.subplot(3, 3, 6)
plt.title("sobel y image",fontdict={'weight':'normal','size': 5})
plt.imshow(sobel_y_img)
plt.subplot(3,3,7)
plt.title("oringal image",fontdict={'weight':'normal','size': 5})
plt.imshow(img,cmap="gray")
plt.subplot(3,3,8)
plt.title("laplace 1 image",fontdict={'weight':'normal','size': 5})
plt.imshow(laplace_1_img)
plt.subplot(3,3,9)
plt.title("laplace 2 image",fontdict={'weight':'normal','size': 5})
plt.imshow(laplace_2_img)
plt.show()