1.前言
我们知道,卷积核(也叫滤波器矩阵)在卷积神经网络中具有非常重要的作用。说白了,CNN主要作用在于提取图像的各种特征图(feature maps).
CNN主要是通过卷积运算来完成特征提取的。图像卷积运算,主要是通过设定各种特征提取滤波器矩阵(卷积核,通常设定大小为3x3,或者5x5的矩阵),然后使用该卷积核在原图像矩阵(图像实际是像素值构成的矩阵)‘滑动’,实现卷积运算。如果对卷积运算还不太明白的,可以去看吴恩达的课程,他已经介绍的很详细了。本文重点在于,使用python来实现卷积运算,让大家可以看到实际的卷积运算结果,从而对CNN提取特征有比较直观的认识,进而更好地去理解基于卷积神经网络的图像识别,目标检测等深度学习算法。
2.自定义卷积核,用numpy完成图像卷积运算,生成对应特征图:
"""
@Project Name: CNN featuremap
@Author: milanboy
@Time: 2019-06-27, 09:37
@Python Version: python3.6
@Coding Scheme: utf-8
@Interpreter Name: PyCharm
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
def conv(image, kernel, mode='same'):
if mode == 'fill':
h = kernel.shape[0] // 2
w = kernel.shape[1] // 2
image = np.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 = np.dstack([conv_b, conv_g, conv_r])
return res
def _convolve(image, kernel):
h_kernel, w_kernel = kernel.shape
h_image, w_image = image.shape
res_h = h_image - h_kernel + 1
res_w = w_image - w_kernel + 1
res = np.zeros((res_h, res_w), np.uint8)
for i in range(res_h):
for j in range(res_w):
res[i, j] = normal(image[i:i + h_kernel, j:j + w_kernel], kernel)
return res
def normal(image, kernel):
res = np.multiply(image, kernel).sum()
if res > 255:
return 255
elif res<0:
return 0
else:
return res
if __name__ == '__main__':
path = './img/doramon.jpeg' # 原图像路径
image = cv2.imread(path)
#kernel 是一个3x3的边缘特征提取器,可以提取各个方向上的边缘
#kernel2 是一个5x5的浮雕特征提取器。
kernel1 = np.array([
[1, 1, 1],
[1, -7.5, 1],
[1, 1, 1]
])
kernel2 = np.array([[-1, -1, -1, -1, 0],
[-1, -1, -1, 0, 1],
[-1, -1, 0, 1, 1],
[-1, 0, 1, 1, 1],
[0, 1, 1, 1, 1]])
res = conv(image, kernel1, 'fill')
plt.imshow(res)
plt.savefig('./out/filtered_picdoramon01.jpg', dpi=600)
plt.show()
3. 实验结果
边缘特征提取
浮雕特征提取器
来张偶像的照片(嘻嘻…)