<h3 dir="auto">System information (version)</h3>
<ul dir="auto">
<li>OpenCV =&gt; 4.1.1</li>
<li>Operating System / Platform =&gt; Windows 64 Bit</li>
<li>Compiler =&gt; Qt Qreator</li>
</ul>
<h3 dir="auto">Detailed description</h3>
<p dir="auto">I've trained a custom Tensorflow-Model (completely from scratch, no transfer-training) and I can predict my Model inside my training framework (tensorpack) without any issues. Now I want to deploy my Model into openCV to use it in my main project. I know that the following steps have to be made to succesfully load my model into openCV:</p>
<ol dir="auto">
<li>Freeze the Graph and generate a frozenGraph.pb with tf.optimize_for_inference  // DONE</li>
<li>Generate a config.pbtxt File with tf.train.write_graph(frozenGraph, asText=True) // DONE</li>
</ol>
<p dir="auto">However, I cannot load my model into openCV. I've tried differenct approaches and always get an exception. However, the exceptions differs based on the following factors:</p>
<p dir="auto"><strong>A.</strong> Net ub6net = readNetFromTensorflow (model) // ONLY PB FILE</p>
<p dir="auto"><strong>A.1 - optimize_for_inference disabled:</strong>  Input Node not found Exception<br>
<strong>A.2 - optimize_for_inference enabled:</strong>  nodesMapIt != nodesMap.end() in func sortByExecutionOrder</p>
<p dir="auto"><strong>B.</strong> Net ub6net = readNetFromTensorflow (model, config) // PB and PBTXT</p>
<p dir="auto"><strong>B.1 - optimize_for_inference disabled:</strong> Assertion failed in function 'addConstNodes'<br>
<strong>B.2 - optimize_for_inference enabled:</strong> Assertion failed in function 'addConstNodes'</p>
<hr>
<p dir="auto">It does not seem to make a difference if I use optimize_for_inference when I read the network with the pbtxt and pb File, I get the same Exception in both cases.</p>
<p dir="auto"><strong>My Code to generate the pb and pbtxt file:</strong></p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="# -*- coding: utf-8 -*-
# File: export.py

import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
from tensorflow.python.tools import optimize_for_inference_lib

from ..compat import is_tfv2, tfv1
from ..input_source import PlaceholderInput
from ..tfutils.common import get_tensors_by_names, get_tf_version_tuple
from ..tfutils.tower import PredictTowerContext
from ..utils import logger

__all__ = ['ModelExporter']


class ModelExporter(object):
    &quot;&quot;&quot;Export models for inference.&quot;&quot;&quot;

    def __init__(self, config):
        &quot;&quot;&quot;Initialise the export process.
        Args:
            config (PredictConfig): the config to use.
                The graph will be built with the tower function defined by this `PredictConfig`.
                Then the input / output names will be used to export models for inference.
        &quot;&quot;&quot;
        super(ModelExporter, self).__init__()
        self.config = config

    def export_compact(self, filename, optimize=True, toco_compatible=False):
        &quot;&quot;&quot;Create a self-contained inference-only graph and write final graph (in pb format) to disk.
        Args:
            filename (str): path to the output graph
            optimize (bool): whether to use TensorFlow's `optimize_for_inference`
                to prune and optimize the graph. This does not work on all types of graphs.
            toco_compatible (bool): See TensorFlow's
                `optimize_for_inference
                &lt;https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/optimize_for_inference.py&gt;`_
                for details. Only available after TF 1.8.
        &quot;&quot;&quot;
        if toco_compatible:
            assert optimize, &quot;toco_compatible is only effective when optimize=True!&quot;
        self.graph = self.config._maybe_create_graph()
        with self.graph.as_default():
            input = PlaceholderInput()
            input.setup(self.config.input_signature)
            with PredictTowerContext(''):
                self.config.tower_func(*input.get_input_tensors())

            input_tensors = get_tensors_by_names(self.config.input_names)
            output_tensors = get_tensors_by_names(self.config.output_names)

            self.config.session_init._setup_graph()
            # we cannot use &quot;self.config.session_creator.create_session()&quot; here since it finalizes the graph
            sess = tfv1.Session(config=tfv1.ConfigProto(allow_soft_placement=True))
            self.config.session_init._run_init(sess)

            dtypes = [n.dtype for n in input_tensors]

            # freeze variables to constants
            frozen_graph_def = graph_util.convert_variables_to_constants(
                sess,
                self.graph.as_graph_def(),
                [n.name[:-2] for n in output_tensors],
                variable_names_whitelist=None,
                variable_names_blacklist=None)

            # prune unused nodes from graph
            if optimize:
                toco_args = () if get_tf_version_tuple() &lt; (1, 8) else (toco_compatible, )
                frozen_graph_def = optimize_for_inference_lib.optimize_for_inference(
                    frozen_graph_def,
                    [n.name[:-2] for n in input_tensors],
                    [n.name[:-2] for n in output_tensors],
                    [dtype.as_datatype_enum for dtype in dtypes],
                    *toco_args)

            tf.train.write_graph(frozen_graph_def, filename, 'ub6_model.pb', as_text=False)
            logger.info(&quot;Output graph written to {}.&quot;.format(filename))
            tf.train.write_graph(frozen_graph_def, filename, 'ub6_config.pbtxt', as_text=True)
            logger.info(&quot;Output graph written to {}.&quot;.format(filename))"><pre class="notranslate"><code class="notranslate"># -*- coding: utf-8 -*-
# File: export.py

import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
from tensorflow.python.tools import optimize_for_inference_lib

from ..compat import is_tfv2, tfv1
from ..input_source import PlaceholderInput
from ..tfutils.common import get_tensors_by_names, get_tf_version_tuple
from ..tfutils.tower import PredictTowerContext
from ..utils import logger

__all__ = ['ModelExporter']


class ModelExporter(object):
    """Export models for inference."""

    def __init__(self, config):
        """Initialise the export process.
        Args:
            config (PredictConfig): the config to use.
                The graph will be built with the tower function defined by this `PredictConfig`.
                Then the input / output names will be used to export models for inference.
        """
        super(ModelExporter, self).__init__()
        self.config = config

    def export_compact(self, filename, optimize=True, toco_compatible=False):
        """Create a self-contained inference-only graph and write final graph (in pb format) to disk.
        Args:
            filename (str): path to the output graph
            optimize (bool): whether to use TensorFlow's `optimize_for_inference`
                to prune and optimize the graph. This does not work on all types of graphs.
            toco_compatible (bool): See TensorFlow's
                `optimize_for_inference
                &lt;https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/optimize_for_inference.py&gt;`_
                for details. Only available after TF 1.8.
        """
        if toco_compatible:
            assert optimize, "toco_compatible is only effective when optimize=True!"
        self.graph = self.config._maybe_create_graph()
        with self.graph.as_default():
            input = PlaceholderInput()
            input.setup(self.config.input_signature)
            with PredictTowerContext(''):
                self.config.tower_func(*input.get_input_tensors())

            input_tensors = get_tensors_by_names(self.config.input_names)
            output_tensors = get_tensors_by_names(self.config.output_names)

            self.config.session_init._setup_graph()
            # we cannot use "self.config.session_creator.create_session()" here since it finalizes the graph
            sess = tfv1.Session(config=tfv1.ConfigProto(allow_soft_placement=True))
            self.config.session_init._run_init(sess)

            dtypes = [n.dtype for n in input_tensors]

            # freeze variables to constants
            frozen_graph_def = graph_util.convert_variables_to_constants(
                sess,
                self.graph.as_graph_def(),
                [n.name[:-2] for n in output_tensors],
                variable_names_whitelist=None,
                variable_names_blacklist=None)

            # prune unused nodes from graph
            if optimize:
                toco_args = () if get_tf_version_tuple() &lt; (1, 8) else (toco_compatible, )
                frozen_graph_def = optimize_for_inference_lib.optimize_for_inference(
                    frozen_graph_def,
                    [n.name[:-2] for n in input_tensors],
                    [n.name[:-2] for n in output_tensors],
                    [dtype.as_datatype_enum for dtype in dtypes],
                    *toco_args)

            tf.train.write_graph(frozen_graph_def, filename, 'ub6_model.pb', as_text=False)
            logger.info("Output graph written to {}.".format(filename))
            tf.train.write_graph(frozen_graph_def, filename, 'ub6_config.pbtxt', as_text=True)
            logger.info("Output graph written to {}.".format(filename))
</code></pre></div>
<h3 dir="auto">Steps to reproduce</h3>
<p dir="auto"><strong>Update:</strong> Model-Files are in my comment below</p>
<p dir="auto"><strong>My OpenCV Code:</strong></p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="#include &lt;opencv2/dnn.hpp&gt;

String model = &quot;Path/ub6_model.pb&quot;;
String config = &quot;Path/ub6_config.pbtxt&quot;;

Net ub6net = cv::dnn::readNetFromTensorflow(model, config);
// Net ub6net = cv::dnn::readNetFromTensorflow(model);
ub6net.setPreferableBackend(DNN_BACKEND_OPENCV);
ub6.net.setPreferableTarget(DNN_TARGET_CPU);"><pre class="notranslate"><code class="notranslate">#include &lt;opencv2/dnn.hpp&gt;

String model = "Path/ub6_model.pb";
String config = "Path/ub6_config.pbtxt";

Net ub6net = cv::dnn::readNetFromTensorflow(model, config);
// Net ub6net = cv::dnn::readNetFromTensorflow(model);
ub6net.setPreferableBackend(DNN_BACKEND_OPENCV);
ub6.net.setPreferableTarget(DNN_TARGET_CPU);
</code></pre></div>
<h5 dir="auto">System information (version)</h5>

<ul dir="auto">
<li>OpenCV =&gt; :3..4.3 / tried 4.0 alpha as well</li>
<li>Operating System / Platform =&gt; :ubuntu 16</li>
</ul>
<h5 dir="auto">Detailed description</h5>
<p dir="auto">I successfully transported some of  ssd model trained in tensorflow and listed <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md">here</a> as per instruction given <a href="https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API">here</a>. I tried generating config file for ssd_mobilenet_v1_fpn_coco model.I am getting error</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="  File &quot;/home/admin-pc/object_detection_eval/obj_det/tf_text_graph_ssd.py&quot;, line 30, in createSSDGraph
    ssd_anchor_generator = config['anchor_generator'][0]['ssd_anchor_generator'][0]
KeyError: 'ssd_anchor_generator'"><pre class="notranslate"><code class="notranslate">  File "/home/admin-pc/object_detection_eval/obj_det/tf_text_graph_ssd.py", line 30, in createSSDGraph
    ssd_anchor_generator = config['anchor_generator'][0]['ssd_anchor_generator'][0]
KeyError: 'ssd_anchor_generator'
</code></pre></div>
<p dir="auto">when i checked there is multiple_anchor_generator rather than ssd_anchor_generator with different hyper param . Should i have to modify tf_text_graph_ssd.py , will this serve purpose?. Any specific suggestions or help appreciated . Thanks in advance</p>
<h5 dir="auto">Steps to reproduce</h5>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="python tf_text_graph_ssd.py --input /path/to/model.pb --config /path/to/pipeline.config  --output 'graph.pbtxt' 

"><pre class="notranslate"><code class="notranslate">python tf_text_graph_ssd.py --input /path/to/model.pb --config /path/to/pipeline.config  --output 'graph.pbtxt' 


</code></pre></div>
<p dir="auto">--&gt;</p>