可能是由于每次循环中都要遍历整个训练集,计算欧氏距离造成的。可以考虑以下优化:

  1. 将训练集的数据预处理并缓存到内存中,避免每次循环都要从磁盘读取数据。

  2. 在人脸检测到后,只对检测到的人脸进行预测,而不是遍历整个训练集。

  3. 可以考虑使用GPU或者Ascend等加速设备,加速模型推理过程。

  4. 可以将模型转换成MindSpore Lite模型,使用MindSpore Lite推理引擎进行推理,可以进一步提高推理速度。

以下是对代码的一些改进:

  1. 在train_resnet函数中,将训练集的数据预处理并缓存到内存中:
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)

# 将数据预处理并缓存到内存中
train_data = []
for f in ds_train.create_dict_iterator(output_numpy=True):
    train_data.append(f)
  1. 在人脸检测到后,只对检测到的人脸进行预测:
if not rect is None:
    for (x, y, w, h) in rect:
        face = gray[y:y + w, x:x + h].astype(np.float32)  # 数值转换
        face = cv2.resize(face, (100, 100))
        cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2)  # 画出矩形框
        #k = cv2.waitKey(100)  # 每0.1秒读取一次键盘
        min_d = 1000000000000
        c = -1
        for f in train_data:  # 遍历预处理后的训练数据
            d = ((face - f['data']) ** 2).sum()  # 计算test和训练图片的欧氏距离
            if d < min_d:
                min_d = d
                label1 = f['label']
                label_counter = Counter(label1)
                most_common_label = label_counter.most_common(1)[0][0]
                c = most_common_label
        if min_d < 200000000000:
            cv2.putText(img1, subjects[c], (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
        else:
            label = 'unknown'
            cv2.putText(img1, label, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
  1. 可以考虑使用GPU或者Ascend等加速设备,加速模型推理过程。可以在load_model_from_ckpt函数中设置device_target为GPU或Ascend。

  2. 可以将模型转换成MindSpore Lite模型,使用MindSpore Lite推理引擎进行推理,可以进一步提高推理速度。MindSpore Lite模型转换可以参考MindSpore Lite官方文档。

def load_model_from_ckpt contextset_contextmode=contextGRAPH_MODE device_target=CPU # 创建ResNet模型 network = ResNetResidualBlock2222 # 加载ckpt文件中的模型参数 param_dict = load_checkpointDpythonpr

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

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