def train_resnet(): context.set_context(mode=context.GRAPH_MODE, device_target='CPU') train_dataset_generator = TrainDatasetGenerator('D:/pythonproject2/digital_mindspore/dataset') 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=4, drop_remainder=True) network = load_model_from_ckpt() net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.001, momentum=0.9) #time_cb = TimeMonitor(data_size=ds_train.get_dataset_size()) #config_ck = CheckpointConfig(save_checkpoint_steps=10,keep_checkpoint_max=10) #config_ckpt_path = 'D:/pythonproject2/ckpt/' #ckpoint_cb = ModelCheckpoint(prefix='checkpoint_resnet', directory=config_ckpt_path, config=config_ck)

model = Model(network, net_loss, net_opt, metrics={'Accuracy': Accuracy()})
#epoch_size = 20
#print('============== Starting Training =============')
#model.train(epoch_size, ds_train, callbacks=[time_cb, ckpoint_cb, LossMonitor()])
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')  # 加载检测器

cap = cv2.VideoCapture(0)
stop = False
while not stop:
    success, img = cap.read()
    subjects = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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 predicted_class[0] == len(subjects)-1:
                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()  # 释放窗口
人脸识别系统:基于ResNet模型的实时识别,支持未知人脸识别

原文地址: https://www.cveoy.top/t/topic/jqBs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录