通过两个函数 f x f_{x} fx 和 g x g_{x} gx 生成第三个函数 T x T_{x} Tx 的一种数学算子
如何通俗易懂地解释卷积?马同学 知乎详解
( f ⋅ g ) ( n ) = ∫ 0 n f ( x ) ⋅ g ( n − x ) d x = > ∑ x = 0 n f ( x ) ⋅ g ( n − x ) (f \cdot g)_{(n)} = \int_0^n f_{(x)}\cdot g_{(n-x)}\,{\rm d}x=>\sum_{x=0}^n f_{(x)}\cdot g_{(n-x)} (f⋅g)(n)=∫0nf(x)⋅g(n−x)dx=>x=0∑nf(x)⋅g(n−x)
import numpy
def normal(image, kernel):
res = numpy.multiply(image, kernel).sum()
if res > 255:
return 255
else:
return res
def _convolve(img_single, kernel):
h_kernel, w_kernel = kernel.shape
h_image, w_image = img_single.shape
# 原图大小的矩形
res_h = h_image - h_kernel + 1
res_w = w_image - w_kernel + 1
# 设置一个和传进来的img一样的维度数组 并赋值为零
res = numpy.zeros((res_h, res_w), numpy.uint8)
for i in range(res_h):
for j in range(res_w):
res[i, j] = normal(img_single[i:i+h_kernel, j:j+w_kernel], kernel)
return res
def conv(image, kernel):
h = kernel.shape[0] // 2
w = kernel.shape[1] // 2
# resize to image, padding size (h, w)
image = numpy.pad(image, ((h, h), (w, w), (0, 0)), 'constant')
conv_b = _convolve(image[..., 0], kernel)
conv_g = _convolve(image[..., 1], kernel)
conv_r = _convolve(image[..., 2], kernel)
res = numpy.dstack([conv_b, conv_g, conv_r])
return res