手动实现一个卷积
其实就是数字图像处理的作业= =其实有时间的话想搞一下im2col,不过也没啥用,应该直接用框架就好了
计算公式
输入图片大小 W×W Filter大小 F×F 步长 S padding的像素数 P
N = (W − F + 2P )/S+1
padding = ‘SAME’ => W = N
S(W-1) = W-F+2P P = ((S-1)W-S+F)/2
代码习惯用jupyter写了。。。罪恶的循环啊。。。
from scipy.misc import imread,imshow,imsave
import numpy as np
img = np.floor(imread("/home/ryan/Desktop/cat.jpg"))
# 平滑和laplace
kernel = np.ones([3,3])/9
kernel = np.array([
[0,-1,0],
[-1,4,-1],
[0,-1,0]
])
# 上图计算各种参数
shape = img.shape
stride = 1
S = stride
F = 3
W = shape[0]
H = shape[1]
Pw = round(((S-1)*W-S+F)/2)
Ph = round(((S-1)*H-S+F)/2)
# padding
padding_img = np.zeros([W+2*Pw,H+2*Ph,shape[2]])
for c in range(shape[2]):
padding_img[Pw:W+Pw,Ph:H+Ph,c] = img[:,:,c]
output = np.zeros_like(a=padding_img)
#convolution
for c in range(shape[2]):
for i in range(Pw, shape[0]+Pw,stride):
for j in range(Ph,shape[1]+Ph,stride):
output[i-Pw,j-Ph,c] = np.sum(padding_img[i-Pw:i+Pw+1,j-Ph:j+Ph+1,c]*kernel)
imshow(output)
原来的小猫
小猫现在长这样