这篇教程卷积神经网络(CNN)中的卷积核到底是如何提取图像特征的(python实现图像卷积运算)写得很实用,希望能帮到您。
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)
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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
3. 实验结果
边缘特征提取




浮雕特征提取器
来张偶像的照片(嘻嘻…)


边缘检测是图像处理和计算机视觉中的基本问题 传统情感分类方法与深度学习的情感分类方法对比 |