深度神经网络——转换 TensorFlow 分类模型并用 OpenCV Python 发布 OpenCV v4.8.0

本文介绍了如何使用Python将TensorFlow模型转换为OpenCVDNN格式,以在MobileNet架构上运行并进行评估。步骤包括获取冻结图、读取模型、预处理图像和比较OpenCV与TensorFlow的预测结果。
摘要由CSDN通过智能技术生成
原作者Anastasia Murzova
兼容性OpenCV >= 4.5

目标

在本教程中,您将学习如何

  • 获取 TensorFlow (TF) 分类模型的冻结图
  • 使用 OpenCV Python API 运行转换后的 TensorFlow 模型
  • 获得 TensorFlow 和 OpenCV DNN 模型的评估结果

我们将以 MobileNet 架构为例,探讨上述要点。

简介

让我们简要了解一下 TensorFlow 模型与 OpenCV API 转换管道中涉及的关键概念。将 TensorFlow 模型转换为 cv.dnn.Net 的第一步是获取冻结的 TF 模型图。冻结图定义了模型图结构与所需变量(如权重)保留值的组合。冻结图通常保存在 protobuf (.pb) 文件中。模型 .pb 文件生成后,可以使用 cv.dnn.readNetFromTensorflow 函数读取。

要求

要使用下面的代码进行实验,您需要安装一组库。为此,我们将使用带有 python3.7+ 的虚拟环境:

virtualenv -p /usr/bin/python3.7 <env_dir_path>
source <env_dir_path>/bin/activate

要从源代码构建 OpenCV-Python,请遵循 OpenCV 简介 中的相应说明。

在开始安装库之前,可以自定义 requirements.txt,排除或包含(例如,opencv-python)某些依赖项。下面一行将启动需求安装到先前激活的虚拟环境中:

pip install -r requirements.txt

实践

在这一部分,我们将介绍以下几点:

  1. 创建 TF 分类模型转换管道并提供推论
  2. 评估和测试 TF 分类模型

如果您只想运行评估或测试模型管道,可以跳过 "模型转换管道 "教程部分。

模型转换管道

本子章的代码位于 dnn_model_runner 模块中,可通过以下命令行执行:

python -m dnn_model_runner.dnn_conversion.tf.classification.py_to_py_mobilenet

以下代码包含下列步骤的说明:

  1. 实例化 TF 模型
  2. 创建 TF 冻结图
  3. 使用 OpenCV API 读取 TF 冻结图
  4. 准备输入数据
  5. 提供推理
# 初始化 TF MobileNet 模型
original_tf_model = MobileNet(
    include_top=True、
    weights="imagenet"
)
# 获取 TF 冻结图路径
full_pb_path = get_tf_model_proto(original_tf_model)
# 使用 OpenCV API 读取冻结图
opencv_net = cv2.dnn.readNetFromTensorflow(full_pb_path)
print("OpenCV 模型已成功读取。模型层: \n", opencv_net.getLayerNames())
# 获取预处理图像
input_img = get_preprocessed_img("../data/squirrel_cls.jpg")
# 获取图像网络标签
imagenet_labels = get_imagenet_labels("../data/dnn/classification_classes_ILSVRC2012.txt")
# 获取 OpenCV DNN 预测结果
get_opencv_dnn_prediction(opencv_net, input_img, imagenet_labels)
# 获取 TF 模型预测结果
get_tf_dnn_prediction(original_tf_model, input_img, imagenet_labels)

为了提供模型推理,我们将使用下面与 ImageNet 类 ID 335 相对应的松鼠照片(采用 CC0 许可):

狐松鼠,东部狐松鼠,Sciurus niger

在这里插入图片描述

分类模型输入图像

为了对预测结果进行标签解码,我们还需要 imagenet_classes.txt 文件,其中包含 ImageNet 类别的完整列表。

让我们以预训练的 TF MobileNet 为例,深入了解每个步骤:

  • 实例化 TF 模型:
# 初始化 TF MobileNet 模型
original_tf_model = MobileNet(
    include_top=True、
    weights="imagenet"
)
  • 创建 TF 冻结图
# 为 .pb 模型定义目录
pb_model_path = "models" # 定义 .pb 模型的名称
# 定义 .pb 模型的名称
pb_model_name = "mobilenet.pb" # 为进一步转换的模型创建目录
# 为进一步转换的模型创建目录
os.makedirs(pb_model_path, exist_ok=True)
# 获取模型 TF 图
tf_model_graph = tf.function(lambda x: tf_model(x))
# 获取具体函数
tf_model_graph = tf_model_graph.get_concrete_function(
    tf.TensorSpec(tf_model.inputs[0].shape, tf_model.inputs[0].dtype))
# 获取冻结的具体函数
frozen_tf_func = convert_variables_too_constants_v2(tf_model_graph)
# 获得冻结图形
frozen_tf_func.graph.as_graph_def()
# 保存完整的 tf 模型
tf.io.write_graph(graph_or_graph_def=frozen_tf_func.graph.as_graph_def() # 保存完整的 tf 模型
                  logdir=pb_model_path、
                  name=pb_model_name、
                  as_text=False)

成功执行上述代码后,我们将在 models/mobilenet.pb 中得到一个冻结图。

# 获取 TF 冻结图路径
full_pb_path = get_tf_model_proto(original_tf_model)
  • 使用 cv2.dnn.blobFromImage 函数准备输入数据:
# 读取图像
input_img = cv2.imread(img_path, cv2.IMREAD_COLOR)
input_img = input_img.astype(np.float32)


# 定义预处理参数
mean = np.array([1.0, 1.0, 1.0]) * 127.5
scale= 1 / 127.5
# 准备输入 blob 以拟合模型输入:
# 减去平均值
# 2. 将像素值从 0 调整为 1
input_blob = cv2.dnn.blobFromImage(
    image=input_img、
    scalefactor=scale、
    size=(224, 224), # 图像目标尺寸
    mean=mean、
    swapRB=True, # BGR -> RGB
    crop=True # 居中裁剪
)
print("Input blob shape: {}\n".format(input_blob.shape))

请注意 cv2.dnn.blobFromImage 函数中的预处理顺序。首先减去平均值,然后将像素值乘以定义的比例。因此,为了重现 TF mobilenet.preprocess_input 函数中的图像预处理流程,我们将平均值乘以 127.5。

这样就得到了 4 维的 input_blob

输入 blob 的形状:(1, 3, 224, 224
# 设置 OpenCV DNN 输入
opencv_net.setInput(preproc_img)
# OpenCV DNN 推理
out = opencv_net.forward()
print("OpenCV DNN prediction: \n")
print("* shape: ", out.shape)
# 获取预测的类 ID
imagenet_class_id = np.argmax(out)
# 获取置信度
confidence = out[0][imagenet_class_id]print("* class ID: {}, label: {}".format(imagenet_class_id, imagenet_labels[imagenet_class_id]))
print("* confidence: {:.4f}\n".format(confidence))

执行上述代码后,我们将得到以下输出结果:

OpenCV DNN 预测:
* shape: (1, 1000)
* 类 ID: 335, label: fox squirrel, eastern fox squirrel, Sciurus niger
* 置信度 0.9525
  • 提供 TF MobileNet 推论:
# 推论
preproc_img = preproc_img.transpose(0, 2, 3, 1)
print("TF input blob shape: {}\n".format(preproc_img.shape))
out = original_net(preproc_img)
print("\nTensorFlow 模型预测:\n")
print("* shape: ", out.shape)
# 获取预测的类 ID
imagenet_class_id = np.argmax(out)
print("* class ID: {}, label: {}".format(imagenet_class_id, imagenet_labels[imagenet_class_id]))
# 获取置信度
confidence = out[0][imagenet_class_id]print("* confidence: {:.4f}".format(confidence))

为了拟合 TF 模型输入,对 input_blob 进行了转置:

TF 输入 Blob 的形状:(1, 224, 224, 3)

TF 推理结果如下:

TensorFlow 模型预测:
* 形状:(11000* 类 ID: 335, label: fox squirrel, eastern fox squirrel, Sciurus niger
* 置信度 0.9525

从实验中可以看出,OpenCV 和 TF 的推理结果相同。

模型评估

dnn/samples dnn_model_runner 模块允许在 ImageNet 数据集上运行完整的评估管道,并对以下 TensorFlow 分类模型进行测试:

  • vgg16
  • vgg19
  • resnet50
  • resnet101
  • resnet152
  • densenet121
  • densenet169
  • densenet201
  • inceptionresnetv2
  • inceptionv3
  • mobilenet
  • mobilenetv2
  • nasnetlarge
  • nasnetmobile
  • xception

该列表还可通过进一步适当的评估管道配置进行扩展。

评估模式

以下一行表示模块在评估模式下运行:

python -m dnn_model_runner.dnn_conversion.tf.classification.py_to_py_cls--model_name<tf_cls_model_name>

从列表中选择的分类模型将被读入 OpenCV cv.dnn_Net 对象。TF 和 OpenCV 模型的评估结果(准确率、推理时间、L1)将写入日志文件。推理时间值也将以图表形式显示,以概括所获得的模型信息。

必要的评估配置已在 test_config.py 中定义,并可根据数据位置的实际路径进行修改:

@dataclass
class TestClsConfig:
    batch_size: int = 50
    frame_size: int = 224
    img_root_dir: str = "./ILSVRC2012_img_val"
    # location of image-class matching
    img_cls_file: str = "./val.txt"
    bgr_to_rgb: bool = True

TestClsConfig 中的值可根据所选模型进行自定义。

要启动 TensorFlow MobileNet 评估,请运行以下一行:

python -m dnn_model_runner.dnn_conversion.tf.classification.py_to_py_cls --model_name mobilenet

脚本启动后,包含评估数据的日志文件将在 dnn_model_runner/dnn_conversion/logs 中生成:

===== 正在使用以下参数对模型进行评估:
    * 值数据位置:./ILSVRC2012_img_val
    * 日志文件位置:dnn_model_runner/dnn_conversion/logs/TF_mobilenet_log.txt

测试模式

下面一行表示在测试模式下运行模块,即提供模型推理的步骤:

python -m dnn_model_runner.dnn_conversion.tf.classification.py_to_py_cls --model_name <tf_cls_model_name> --test True --default_img_preprocess <True/False> --evaluate False

这里的 default_img_preprocess 关键字定义您是想用某些特定值参数化模型测试过程,还是使用默认值,例如 scalemeanstd

测试配置在 test_config.py TestClsModuleConfig 类中表示:

@dataclass
class TestClsModuleConfig:
    cls_test_data_dir: str = "../data"
    test_module_name: str = "classification"
    test_module_path: str = "classification.py"
    input_img: str = os.path.join(cls_test_data_dir, "squirrel_cls.jpg")
    model: str = ""
    frame_height: str = str(TestClsConfig.frame_size)
    frame_width: str = str(TestClsConfig.frame_size)
    scale: str = "1.0"
    mean: List[str] = field(default_factory=lambda: ["0.0", "0.0", "0.0"])
    std: List[str] = field(default_factory=list)
    crop: str = "False"
    rgb: str = "True"
    rsz_height: str = ""
    rsz_width: str = ""
    classes: str = os.path.join(cls_test_data_dir, "dnn", "classification_classes_ILSVRC2012.txt")

默认图像预处理选项在 default_preprocess_config.py 中定义。例如,对于 MobileNet

tf_input_blob = {
    "mean": ["127.5", "127.5", "127.5"],
    "scale": str(1 / 127.5),
    "std": [],
    "crop": "True",
    "rgb": "True"
}

samples/dnn/classification.py 中表示的模型测试基础可通过在 --input 中提供的转换模型和为 cv.dnn.blobFromImage 配置的参数自主执行。

要使用 dnn_model_runner 从头开始重现 "模型转换管道 "中描述的 OpenCV 步骤,请执行以下一行:

python -m dnn_model_runner.dnn_conversion.tf.classification.py_too_py_cls --model_name mobilenet --test True --default_img_preprocess True --evaluate False

网络预测结果显示在输出窗口的左上角:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值