赞
踩
让我们简要回顾一下使用 OpenCV API 进行 TensorFlow 模型转换的管道中涉及的关键概念。将 TensorFlow 模型转换为 cv.dnn.Net 的第一步是获取冻结的 TF 模型图。冻结图定义了模型图结构与所需变量(例如权重)的保留值的组合。通常冻结的图形保存在 protobuf () 文件中。模型文件生成后,可以使用 cv.dnn.readNetFromTensorflow 函数读取它。.pb
.pb
为了能够试验以下代码,您需要安装一组库。为此,我们将使用 python3.7+ 的虚拟环境:
对于从源代码构建 OpenCV-Python,请遵循 OpenCV 简介中的相应说明。
在开始安装库之前,可以自定义要求 .txt,排除或包含(例如)某些依赖项。以下行将需求安装启动到先前激活的虚拟环境中:opencv-python
在这一部分中,我们将介绍以下几点:
如果只想运行评估或测试模型管道,可以跳过“模型转换管道”教程部分。
本子章中的代码位于模块中,可以使用以下行执行:dnn_model_runner
以下代码包含下面列出的步骤的说明:
# 初始化 TF MobileNet 模型original_tf_model = MobileNet(include_top=真,权重=“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(“../数据/squirrel_cls.jpg“)# 获取 ImageNet 标签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 许可下):
对于所获得的预测的标签解码,我们还需要文件,其中包含 ImageNet 类的完整列表。imagenet_classes.txt
让我们以预训练的 TF MobileNet 为例,更深入地了解每个步骤:
# 初始化 TF MobileNet 模型original_tf_model = MobileNet(include_top=真,权重=“imagenet”)
# 定义 .pb model 的目录pb_model_path = “模型”# 定义 .pb 模型的名称pb_model_name =“移动网.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_to_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,logdir=pb_model_path,名称=pb_model_name,as_text=False)
在上述代码成功执行后,我们将在 中得到一个冻结的图。models/mobilenet.pb
mobilenet.pb
# 获取 TF 冻结图路径full_pb_path = get_tf_model_proto(original_tf_model)
# 读取镜像input_img = cv2.imread(img_path, cv2.IMREAD_COLOR)input_img = input_img.astype(np.float32)# 定义预处理参数均值 = np.array([1.0, 1.0, 1.0]) * 127.5比例 = 1 / 127.5# 准备输入 blob 以适应模型输入:# 1.减去平均值# 2.缩放以设置从 0 到 1 的像素值input_blob = cv2.dnn.blobFromImage(image=input_img,scalefactor=scale,size=(224, 224), # img 目标大小mean=平均值,swapRB=True, # BGR -> RGBcrop=True # 中心裁剪)
请注意 cv2.dnn.blobFromImage 函数中的预处理顺序。首先,减去平均值,然后将像素值乘以定义的刻度。因此,为了重现 TF mobilenet.preprocess_input 函数的图像预处理管道,我们将 乘以 。mean
127.5
结果,获得了 4 维:input_blob
Input blob shape: (1, 3, 224, 224)
# 设置 OpenCV DNN 输入opencv_net.setInput(preproc_img)# OpenCV DNN 推理out = opencv_net.forward()print(“OpenCV DNN 预测:\n”)print(“* 形状: ”, out.shape)# 获取预测的类 IDimagenet_class_id = np.argmax(输出)# 获得信心置信度 = out[0][imagenet_class_id]print(“* 类 ID: {}, label: {}”.format(imagenet_class_id, imagenet_labels[imagenet_class_id]))print(“* 置信度:{:.4f}\n”.format(置信度))
在上述代码执行后,我们将得到以下输出:
# 推理preproc_img = preproc_img.转置(0, 2, 3, 1)print(“TF 输入 blob 形状:{}\n”.format(preproc_img.shape))输出 = original_net(preproc_img)print(“\nTensorFlow 模型预测: \n”)print(“* 形状: ”, out.shape)# 获取预测的类 IDimagenet_class_id = np.argmax(输出)print(“* 类 ID: {}, label: {}”.format(imagenet_class_id, imagenet_labels[imagenet_class_id]))# 获得信心置信度 = out[0][imagenet_class_id]print(“* 置信度:{:.4f}”.format(置信度))
为了适应 TF 模型输入,进行了转置:input_blob
TF 推理结果如下:
从实验中可以看出,OpenCV和TF的推理结果是相等的。
建议的模块允许在 ImageNet 数据集上运行完整的评估管道,并测试以下 TensorFlow 分类模型的执行:dnn/samples
dnn_model_runner
此列表还可以通过进一步适当的评估管道配置进行扩展。
下行表示模块在评估模式下的运行:
从列表中选择的分类模型将被读入 OpenCV 对象。TF 和 OpenCV 模型的评估结果(精度、推理时间、L1)将写入日志文件。推理时间值也将在图表中描述,以概括获得的模型信息。cv.dnn_Net
必要的评估配置在test_config.py中定义,并可根据数据位置的实际路径进行修改:
可以根据所选模型自定义值。TestClsConfig
要启动对 TensorFlow MobileNet 的评估,请运行以下行:
脚本启动后,将在以下位置生成包含评估数据的日志文件:dnn_model_runner/dnn_conversion/logs
以下行表示模块在测试模式下的运行,即它提供了模型推理的步骤:
此处的 key 定义是要使用某些特定值参数化模型测试过程,还是使用默认值,例如 、 或 。default_img_preprocess
scale
mean
std
测试配置在test_config.py类中表示:TestClsModuleConfig
@dataclass类 TestClsModuleConfig:cls_test_data_dir:str = “../数据”test_module_name: str = “classification”test_module_path:str = “classification.py”input_img:str = os.path.join(cls_test_data_dir, “squirrel_cls.jpg”)型号: str = “”frame_height:str = str(TestClsConfig.frame_size)frame_width:str = str(TestClsConfig.frame_size)比例:str = “1.0”mean: List[str] = field(default_factory=lambda: [“0.0”, “0.0”, “0.0”])标准:List[str] = 字段(default_factory=list)裁剪:str = “False”rgb:str = “真”rsz_height:str = “”rsz_width:str = “”类:str = os.path.join(cls_test_data_dir, “dnn”, “classification_classes_ILSVRC2012.txt”)缺省图像预处理选项在 中定义。例如,对于 MobileNet:
default_preprocess_config.py
tf_input_blob = {“平均值”: [“127.5”, “127.5”, “127.5”],“比例”:str(1 / 127.5),“std”:[],“crop”: “真”,“rgb”: “真”}
模型测试的基础在 samples/dnn/classification.py 中表示。 可以使用提供的转换模型和填充的 cv.dnn.blobFromImage 参数自主执行。classification.py
--input
要从头开始重现“模型转换管道”中描述的 OpenCV 步骤,请执行以下行:dnn_model_runner
网络预测显示在输出窗口的左上角:
有需要的小伙伴,可以点击下方链接免费领取或者V扫描下方二维码免费领取
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。