基于MindSpore的ResNet人脸识别模型实现
import numpy as np
import mindspore.dataset as ds
import os
import cv2
import mindspore
import mindspore.nn as nn
from mindspore import Tensor, load_checkpoint, load_param_into_net
from mindspore.common.initializer import Normal
from mindspore import context
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
from mindspore.ops.operations import TensorAdd
from scipy.integrate._ivp.radau import P
from mindspore import Model # 承载网络结构
from mindspore.nn.metrics import Accuracy # 测试模型用
np.random.seed(58)
class BasicBlock(nn.Cell):
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, pad_mode='pad',has_bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, pad_mode='pad', has_bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.downsample = downsample
self.add = TensorAdd()
def construct(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out = self.add(out, identity)
out = self.relu(out)
return out
class ResNet(nn.Cell):
def __init__(self, block, layers, num_classes=11):
super(ResNet, self).__init__()
self.in_channels = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, pad_mode='pad', has_bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='same')
self.layer1 = self.make_layer(block, 64, layers[0])
self.layer2 = self.make_layer(block, 128, layers[1], stride=2)
self.layer3 = self.make_layer(block, 256, layers[2], stride=2)
self.layer4 = self.make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(kernel_size=1, stride=1, pad_mode='valid') # 修改这里
self.flatten = nn.Flatten()
self.fc1 = nn.Dense(512, 100)
self.fc2 = nn.Dense(100, num_classes)
def make_layer(self, block, out_channels, blocks, stride=1):
downsample = None
if stride != 1 or self.in_channels != out_channels:
downsample = nn.SequentialCell([
nn.Conv2d(self.in_channels, out_channels, kernel_size=1, stride=stride, has_bias=False),
nn.BatchNorm2d(out_channels)
])
layers = []
layers.append(block(self.in_channels, out_channels, stride, downsample))
self.in_channels = out_channels
for _ in range(1, blocks):
layers.append(block(out_channels, out_channels))
return nn.SequentialCell(layers)
def construct(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = self.flatten(x)
x = self.fc1(x)
x = self.fc2(x)
return x
class TrainDatasetGenerator:
def __init__(self, file_path):
self.file_path = file_path
self.img_names = os.listdir(file_path)
def __getitem__(self, index):
data = cv2.imread(os.path.join(self.file_path, self.img_names[index]))
label = self.img_names[index].split('_')[0]
label = int(label)
data = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
data = cv2.resize(data, (224, 224))
data = data.transpose().astype(np.float32) / 255.
return data, label
def __len__(self):
return len(self.img_names)
def load_model_from_ckpt():
context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
# 创建ResNet模型
network = ResNet(BasicBlock,[2,2,2,2])
# 加载ckpt文件中的模型参数
param_dict = load_checkpoint('D:/pythonProject7/ckpt/checkpoint_resnet_34-8_25.ckpt')
# 修改全连接层输出维度
param_dict['layer4.1.conv2.weight'] = param_dict['layer4.1.conv2.weight'][:, :, :, :]
param_dict['fc.weight'] = param_dict['fc.weight'][:, :100]
# 将模型参数加载到模型中
load_param_into_net(network, param_dict)
network.fc1 = nn.Dense(512, 100)
network.fc2 = nn.Dense(100, 11)
# 返回模型
return network
def train_resnet():
context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
train_dataset_generator = TrainDatasetGenerator('D:/pythonProject7/train1')
ds_train = ds.GeneratorDataset(train_dataset_generator, ['data', 'label'], shuffle=True)
ds_train = ds_train.shuffle(buffer_size=10)
ds_train = ds_train.batch(batch_size=2, drop_remainder=True)
network = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=11)
net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.001, momentum=0.9)
model = Model(network, net_loss, net_opt, metrics={'Accuracy': Accuracy()})
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') # 加载检测器
threshold = 0.95 # 设置阈值
cap = cv2.VideoCapture(0)
stop = False
while not stop:
success, img = cap.read()
subjects = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'unknown']
# 生成图像的副本,这样就能保留原始图像
img1 = img.copy()
# 检测人脸
# 将测试图像转换为灰度图像,因为opencv人脸检测器需要灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测多尺度图像,返回值是一张脸部区域信息的列表(x,y,宽,高)
rect = face_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
# 如果未检测到面部
if len(rect) == 0:
txt = 'no face!'
cv2.putText(img1, txt, (10, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
if not rect is None:
for (x, y, w, h) in rect:
face = img[y:y + w, x:x + h].astype(np.float32) # 数值转换
face = cv2.resize(face, (100, 100))
face = face.transpose().astype(np.float32) / 255.
face = np.expand_dims(face, axis=0) # 扩展维度,变成(batch_size, channels, height, width)
face = Tensor(face)
cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2) # 画出矩形框
output = network(face)
predicted_class = np.argmax(output.asnumpy(), axis=1)
if output.asnumpy()[0][predicted_class[0]] < threshold:
label = 'unknown'
else:
label = subjects[predicted_class[0]]
cv2.putText(img1, label, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
cv2.imshow('img', img1)
if (cv2.waitKey(1) & 0xFF == ord('q')): # 按下q程序结束
stop = True
cv2.destroyAllWindows() # 释放窗口
if __name__ == '__main__':
train_resnet()
代码说明:
-
环境配置
- 安装MindSpore框架和OpenCV库。
- 设置MindSpore运行环境,指定为CPU模式。
-
模型定义
- 定义
BasicBlock类,代表ResNet中的基本模块,包含两个卷积层、两个BatchNorm层和一个ReLU激活函数。 - 定义
ResNet类,包含完整的ResNet模型结构,包含卷积层、池化层、全连接层等。
- 定义
-
数据集加载
- 定义
TrainDatasetGenerator类,用于加载图像数据,并将图像数据进行预处理,包括转换颜色空间、调整大小、归一化等。
- 定义
-
模型训练
- 创建ResNet模型,并加载预训练的模型权重。
- 定义损失函数、优化器和模型。
- 使用
Model类进行模型训练。
-
人脸识别
- 使用OpenCV加载人脸检测器。
- 实时从摄像头获取视频流。
- 使用人脸检测器检测人脸,并对检测到的人脸进行识别。
- 将识别结果显示在视频窗口上。
代码改进:
-
修改
num_classes参数- 将
ResNet类的num_classes参数设置为11,代表10个类别的人脸和一个“unknown”类别。
- 将
-
调整模型输出维度
- 将模型的最后一个全连接层的输出维度调整为11,对应于11个类别。
-
人脸识别逻辑
- 加入识别结果的阈值判断,如果识别置信度低于阈值,则将结果设置为“unknown”。
错误分析:
- 错误信息 `ValueError: For 'MatMul', the input dimensions must be equal...` 指示在矩阵乘法运算中,两个矩阵的维度不匹配。
- 在模型定义中,最后一个全连接层的输出维度为 11,但输入维度为 512,而之前预训练的模型最后一个全连接层的输出维度是 100,导致 `fc.weight` 矩阵的维度不匹配。
- 将 `fc.weight` 矩阵的维度调整为 100 行 512 列,即 `param_dict['fc.weight'] = param_dict['fc.weight'][:, :100]` 解决了这个问题。
注意:
- 代码中的
'D:/pythonProject7/train1'和'D:/pythonProject7/ckpt/checkpoint_resnet_34-8_25.ckpt'需要替换为实际的数据集路径和模型文件路径。 - 请确保环境配置正确,并安装必要的库。
运行效果:
- 运行代码后,将打开摄像头窗口,并显示人脸识别结果。
- 识别成功的人脸将显示对应的人脸类别,识别失败的人脸将显示“unknown”。
其他优化建议:
- 可以尝试使用不同的模型架构,例如MobileNetV2、EfficientNet等。
- 可以对人脸检测和识别过程进行进一步的优化,例如使用更高效的人脸检测器、优化识别算法等。
- 可以使用更强大的GPU进行训练,提高模型训练效率和识别精度。
总结:
- 本代码示例展示了如何使用MindSpore框架实现ResNet模型进行人脸识别。
- 代码中使用了预训练的模型权重,简化了模型训练过程。
- 代码结合了OpenCV库进行人脸检测,实现了实时人脸识别功能。
希望本代码示例对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/jrzX 著作权归作者所有。请勿转载和采集!