Conversion of TensorFlow Detection Models and Launch with OpenCV Python
Примеры с cv2.imshow требуют сборки OpenCV с GUI. В ноутбуке с headless-версией используйте вывод изображений через Matplotlib.
Conversion of TensorFlow Detection Models and Launch with OpenCV Python
Original author
Anastasia Murzova
Compatibility
OpenCV >= 4.5
In this tutorial you will learn how to:
obtain frozen graphs of TensorFlow (TF) detection models
run converted TensorFlow model with OpenCV Python API
We will explore the above-listed points by the example of SSD MobileNetV1.
Introduction
Let's briefly view the key concepts involved in the pipeline of TensorFlow models transition with OpenCV API. The initial step in the conversion of TensorFlow models into cv.dnn.Net is obtaining the frozen TF model graph. A frozen graph defines the combination of the model graph structure with kept values of the required variables, for example, weights. The frozen graph is saved in protobuf (.pb) files. There are special functions for reading .pb graphs in OpenCV: cv.dnn.readNetFromTensorflow and cv.dnn.readNet.
Requirements
To be able to experiment with the below code you will need to install a set of libraries. We will use a virtual environment with python3.7+ for this:
For OpenCV-Python building from source, follow the corresponding instructions from the Introduction to OpenCV.
Before you start the installation of the libraries, you can customize the requirements.txt, excluding or including (for example, opencv-python) some dependencies. The below line initiates requirements installation into the previously activated virtual environment:
pipinstall -rrequirements.txt
Practice
In this part we are going to cover the following points:
create a TF classification model conversion pipeline and provide the inference
provide the inference, process prediction results
Model Preparation
The code in this subchapter is located in the samples/dnn/dnn_model_runner module and can be executed with the below line:
To initiate the test process we need to provide an appropriate model configuration. We will use ssd_mobilenet_v1_coco.config from TensorFlow Object Detection API. TensorFlow Object Detection API framework contains helpful mechanisms for object detection model manipulations.
We will use this configuration to provide a text graph representation. To generate .pbtxt we will use the corresponding samples/dnn/tf_text_graph_ssd.py script:
After successful execution ssd_mobilenet_v1_coco_2017_11_17.pbtxt will be created.
Before we run object_detection.py, let's have a look at the default values for the SSD MobileNetV1 test process configuration. They are located in models.yml:
There are several helpful parameters, which can be also customized for result corrections: threshold (--thr) and non-maximum suppression (--nms) values.