OpenCV预定义的很多滤波器,也就是滤波函数都会使用——kernel。
kernel从数学上是一个具有奇数行和奇数列的矩阵,用来对一个区域的像素做mix up或者卷积运算。
对于图像像素来说,它是一组权重,它决定了该如何计算目标像素点的新值。
kernel_33 = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
数学上我们设 A A =
书中,修改代码,在Cameo中添加self._curveFilter = filters.BGRPortraCurveFilter()
但是寻不到BGRPortraCurveFilter()
,遂查找,原来是漏写了。。
在utils.py
中添加如下代码:
import cv2, numpy, scipy.interpolate
def createCurveFunc(points):
"""Return a function derived from control points."""
if points is None:
return None
num_points = len(points)
if num_points < 2:
return None
xs, ys = zip(*points)
if num_points < 4:
kind = 'linear'
# 'quadratic' is not implemented.
else:
kind = 'cubic'
return scipy.interpolate.interp1d(xs, ys, kind, bounds_error=False)
def createLookupArray(func, length = 256):
"""Return a lookup for whole-number inputs to a function. The lookup values are clamped to [0, length - 1]."""
if func is None:
return None
lookup_array = numpy.empty(length)
i = 0
while i < length:
func_i = func(i)
lookup_array[i] = min(max(0, func_i), length - 1)
i += 1
return lookup_array
def applyLookupArray(lookup_array, src, dst):
"""Map a source to a destination using a lookup."""
if lookup_array is None:
return
dst[:] = lookup_array[src]
def createCompositeFunc(func0, func1):
"""Return a composite of two functions."""
if func0 is None:
return func1
if func1 is None:
return func0
return lambda x: func0(func1(x))
def createFlatView(array):
"""Return a 1D view of an array of any dimensionality."""
flat_view = array.view()
flat_view.shape = array.size
return flat_view
在filters.py
添加:
class BGRFuncFilter(object):
def __init__(self, vFunc=None, bFunc=None, gFunc=None, rFunc=None, dtype=numpy.uint8) :
length = numpy.iinfo(dtype).max + 1
self._bLookupArray = utils.createLookupArray(utils.createCompositeFunc(bFunc, vFunc), length)
self._gLookupArray = utils.createLookupArray(utils.createCompositeFunc(gFunc, vFunc), length)
self._rLookupArray = utils.createLookupArray(utils.createCompositeFunc(rFunc, vFunc), length)
def apply(self, src, dst) :
"""Apply the filter with a BGR source/destination."""
b, g, r = cv2.split(src)
utils.applyLookupArray(self._bLookupArray, b, b)
utils.applyLookupArray(self._gLookupArray, g, g)
utils.applyLookupArray(self._rLookupArray, r, r)
cv2.merge([ b, g, r ], dst)
class BGRCurveFilter(BGRFuncFilter):
def __init__(self, vPoints=None, bPoints=None, gPoints=None, rPoints=None, dtype=numpy.uint8):
BGRFuncFilter.__init__(self, utils.createCurveFunc(vPoints), utils.createCurveFunc(bPoints),
utils.createCurveFunc(gPoints), utils.createCurveFunc(rPoints), dtype)
class BGRPortraCurveFilter(BGRCurveFilter):
def __init__(self, dtype = numpy.uint8):
BGRCurveFilter.__init__(
self,
vPoints = [ (0, 0), (23, 20), (157, 173), (255, 255) ],
bPoints = [ (0, 0), (41, 46), (231, 228), (255, 255) ],
gPoints = [ (0, 0), (52, 47), (189, 196), (255, 255) ],
rPoints = [ (0, 0), (69, 69), (213, 218), (255, 255) ],
dtype = dtype)