前言
卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络(Feedforward Neural Networks),是深度学习(deep learning)的代表算法之一 。卷积神经网络具有表征学习(representation learning)能力,能够按其阶层结构对输入信息进行平移不变分类(shift-invariant classification),因此也被称为“平移不变人工神经网络(Shift-Invariant Artificial Neural Networks, SIANN)” 。
一、神经网络介绍
1.神经网络说明
参考:神经网络算法
2.神经网络结构
①输入层
用于数据的输入
②卷积层
使用卷积核进行特征提取和特征映射
③激励层
由于卷积也是一种线性运算,因此需要增加非线性映射
④池化层
进行下采样,对特征图稀疏处理,减少数据运算量。
⑤全连接层
通常在CNN的尾部进行重新拟合,减少特征信息的损失
结构图:
二、数据处理
1.数据预处理
采用genki4k人脸数据
如下:
1)将完整人脸提取
def init_file():
num = 0
bar = tqdm(os.listdir(read_path))
for file_name in bar:
bar.desc = "预处理图片: "
# a图片的全路径
img_path = (read_path + "/" + file_name)
# 读入的图片的路径中含非英文
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
# 获取图片的宽高
img_shape = img.shape
img_height = img_shape[0]
img_width = img_shape[1]
# 用来存储生成的单张人脸的路径
# dlib检测
dets = detector(img, 1)
for k, d in enumerate(dets):
if len(dets) > 1:
continue
num += 1
# 计算矩形大小
# (x,y), (宽度width, 高度height)
# pos_start = tuple([d.left(), d.top()])
# pos_end = tuple([d.right(), d.bottom()])
# 计算矩形框大小
height = d.bottom() - d.top()
width = d.right() - d.left()
# 根据人脸大小生成空的图像
img_blank = np.zeros((height, width, 3), np.uint8)
for i in range(height):
if d.top() + i >= img_height: # 防止越界
continue
for j in range(width):
if d.left() + j >= img_width: # 防止越界
continue
img_blank[i][j] = img[d.top() + i][d.left() + j]
img_blank = cv2.resize(img_blank, (200, 200), interpolation=cv2.INTER_CUBIC)
# 保存图片
cv2.imencode('.jpg', img_blank)[1].tofile(save_path + "/" + "file" + str(num) + ".jpg")
logging.info("一共", len(os.listdir(read_path)), "个样本")
logging.info("有效样本", num)
三、模型训练
1、创建模型
# 创建网络
def create_model():
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
return model
2、模型训练
# 训练模型
def train_model(model):
# 归一化处理
train_datagen = ImageDataGenerator(
rescale=1. / 255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True, )
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
# This is the target directory
train_dir,
# All images will be resized to 150x150
target_size=(150, 150),
batch_size=32,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=32,
class_mode='binary')
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=60,
validation_data=validation_generator,
validation_steps=30)
# 保存模型
save_path = "output/model"
if not os.path.exists(save_path):
os.makedirs(save_path)
model.save(save_path + "/smileAndUnsmile.h5")
return history
3、训练结果
准确率:
丢失率:
训练过程:
四、效果演示
1、预测代码
def rec(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dets = detector(gray, 1)
if dets is not None:
for face in dets:
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)
img1 = cv2.resize(img[top:bottom, left:right], dsize=(150, 150))
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img1 = np.array(img1) / 255.
img_tensor = img1.reshape(-1, 150, 150, 3)
prediction = model.predict(img_tensor)
if prediction[0][0] > 0.5:
result = 'unsmile'
else:
result = 'smile'
cv2.putText(img, result, (left, top), font, 2, (0, 255, 0), 2, cv2.LINE_AA)
cv2.imshow('Video', img)
while video.isOpened():
res, img_rd = video.read()
if not res:
break
rec(img_rd)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
2、预测效果
总结
卷积神经网络是近年发展起来,并引起广泛重视的一种高效识别方法。一般地,CNN的基本结构包括两层,其一为特征提取层,每个神经元的输入与前一层的局部接受域相连,并提取该局部的特征。CNN主要用来识别位移、缩放及其他形式扭曲不变性的二维图形,该部分功能主要由池化层实现。卷积神经网络长期以来是图像识别领域的核心算法之一,并在学习数据充足时有稳定的表现 。