2D 卷积
与以为信号一样,我们也可以对 2D 图像实施低通滤波(LPF),高通滤波
(HPF)等。LPF 帮助我们去除噪音,模糊图像。HPF 帮助我们找到图像的边
缘
OpenCV 提供的函数 cv.filter2D() 可以让我们对一幅图像进行卷积操
作。下面我们将对一幅图像使用平均滤波器。下面是一个 5x5 的平均滤波器核:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread(‘opencv_logo.png’)
kernel = np.ones((5,5),np.float32)/25
#cv.Filter2D(src, dst, kernel, anchor=(-1, -1))
#ddepth –desired depth of the destination image;
#if it is negative, it will be the same as src.depth();
#the following combinations of src.depth() and ddepth are supported:
#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
#when ddepth=-1, the output image will have the same depth as the source.
dst = cv2.filter2D(img,-1,kernel)
plt.subplot(121),plt.imshow(img),plt.title(‘Original’)
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title(‘Averaging’)
plt.xticks([]), plt.yticks([])
plt.show()
结果:
均值滤波
img = cv2.imread(‘opencv_logo.png’)
blur = cv2.blur(img,(5,5))
高斯滤波
#你也可以使用函数 cv2.getGaussianKernel() 自己构建一个高斯核。
#0 是指根据窗口大小(5,5)来计算高斯函数标准差
blur = cv2.GaussianBlur(img,(5,5),0)
中值滤波
median = cv2.medianBlur(img,5)