线性滤波与卷积的基本概念
线性滤波可以说是图像处理最基本的方法,它可以允许我们对图像进行处理,产生很多不同的效果。做法很简单。首先,我们有一个二维的滤波器矩阵(有个高大上的名字叫卷积核)和一个要处理的二维图像。然后,对于图像的每一个像素点,计算它的邻域像素和滤波器矩阵的对应元素的乘积,然后加起来,作为该像素位置的值。这样就完成了滤波过程。
import cv2
import numpy
#-卷积/锐化/边缘检测/模糊滤波器详解
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 边缘检测优化方法 先对图像进行模糊处理,再转为为灰度彩色图像,再使用laplacian检测边缘。此方法可较好的避免将噪声错误地识别为边缘。
def strokeEdges(src, dst, blurKsize=7, edgeKsize=5):
if blurKsize >= 3:
blurredSrc = cv2.medianBlur(src, blurKsize)
graySrc = cv2.cvtColor(blurredSrc, cv2.COLOR_BGR2GRAY)
else:
graySrc = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
cv2.Laplacian(graySrc, cv2.CV_8U, graySrc, ksize=edgeKsize)
# cv_show('binary',binary)
normalizedInverseAlpha = (1.0 / 255) * (255 - graySrc)
# cv_show('normalized',normalizedInverseAlpha)
channels = cv2.split(src)
for channel in channels:
channel[:] = channel * normalizedInverseAlpha
# cv_show('channel',channel)
dst = cv2.merge(channels)
return dst
# 一般的卷积滤波器方法
class VConvolutionFilter(object):
# A filter that applies a convolution to V (or all of BGR)
def __init__(self, kernel):
self._kernel = kernel
def apply(self, src):
# Apply the filter with a BGR or gray source /destination
dst = cv2.filter2D(src, -1, self._kernel)
return dst
# 特定的锐化滤波器方法
class shapenFilter(VConvolutionFilter):
# A shapen filter with a 1-pixel radius
def __init__(self):
kernel = numpy.array([
[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1],
]) # 若不想改变图像亮度,则权重加起来为1。若使权重和为0,则得到一个边缘检测核,把边缘转化为白色,把非边缘区域转为黑色,例如下面的FindEdgesFilter方法
VConvolutionFilter.__init__(self, kernel)
# 边缘检测滤波器。
class FindEdgesFilter(VConvolutionFilter):
# An edge-finding filter with a 1-pixel radius
def __init__(self):
kernel = numpy.array([
[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1],
])
VConvolutionFilter.__init__(self, kernel)
# 模糊滤波器,为了达到模糊效果,通常权重和为1,而且临近像素的权重全为正。下面实现一个简单的邻近平均滤波器:
class BlurFilter(VConvolutionFilter):
# A blur filter with a 2-piexl radius
def __init__(self):
kernel = numpy.array([
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
])
VConvolutionFilter.__init__(self, kernel)
# 脊状/浮雕效果滤波器
class EmbossFilter(VConvolutionFilter):
def __init__(self):
kernel = numpy.array([
[-2, -1, 0],
[-1, 9, 1],
[0, 1, 2],
])
VConvolutionFilter.__init__(self, kernel)
image = cv2.imread(r'D:XX.jpg')
dst = numpy.ones((image.shape[0], image.shape[1]), dtype=numpy.int8)
dst = strokeEdges(image, dst)
cv_show('strokeEdges', dst)
shape = shapenFilter()
dst = shape.apply(image)
cv_show('strokeEdges', dst)
FindEdgesFilter = FindEdgesFilter()
dst = FindEdgesFilter.apply(image)
cv_show('FindEdgesFilter', dst)
BlurFilter = BlurFilter()
dst = BlurFilter.apply(image)
cv_show('blurfilter', dst)
EmbossFilter = EmbossFilter()
dst = EmbossFilter.apply(image)
cv_show('EmbossFilter', dst)
参考文献