<h5 dir="auto">System information (version)</h5>

<ul dir="auto">
<li>OpenCV =&gt; 4.1.2</li>
<li>Operating System / Platform =&gt; macOS Catalina, Version 10.15.1</li>
<li>Compiler =&gt; Xcode, Version 11.2.1 (11B500)</li>
</ul>
<h5 dir="auto">Detailed description</h5>
<p dir="auto">I installed opencv4 through homebrew.<br>
Unfortunately, cv::medianBlur() crushed every time it runs.<br>
I checked the input variable format, kernel size as the doc says. I am sure the problem is not caused by these reasons.<br>
I think the problem is from the opencv lib itself. The homebrew installation process summary is as follows:</p>
<blockquote>
<p dir="auto">==&gt; Summary<br>
<g-emoji class="g-emoji" alias="beer" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f37a.png">🍺</g-emoji>  /usr/local/Cellar/opencv/4.1.2: 753 files, 228.2MB<br>
==&gt; Caveats<br>
==&gt; cmake<br>
Emacs Lisp files have been installed to:<br>
/usr/local/share/emacs/site-lisp/cmake<br>
==&gt; openblas<br>
openblas is keg-only, which means it was not symlinked into /usr/local,<br>
because macOS provides BLAS and LAPACK in the Accelerate framework.<br>
For compilers to find openblas you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/openblas/lib"<br>
export CPPFLAGS="-I/usr/local/opt/openblas/include"<br>
For pkg-config to find openblas you may need to set:<br>
export PKG_CONFIG_PATH="/usr/local/opt/openblas/lib/pkgconfig"<br>
==&gt; gettext<br>
gettext is keg-only, which means it was not symlinked into /usr/local,<br>
because macOS provides the BSD gettext library &amp; some software gets confused if both are in the library path.<br>
If you need to have gettext first in your PATH run:<br>
echo 'export PATH="/usr/local/opt/gettext/bin:$PATH"' &gt;&gt; ~/.bash_profile<br>
For compilers to find gettext you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/gettext/lib"<br>
export CPPFLAGS="-I/usr/local/opt/gettext/include"<br>
==&gt; openssl@1.1<br>
A CA file has been bootstrapped using certificates from the system<br>
keychain. To add additional certificates, place .pem files in<br>
/usr/local/etc/openssl@1.1/certs<br>
and run<br>
/usr/local/opt/openssl@1.1/bin/c_rehash<br>
openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,<br>
because openssl/libressl is provided by macOS so don't link an incompatible version.<br>
If you need to have openssl@1.1 first in your PATH run:<br>
echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' &gt;&gt; ~/.bash_profile<br>
For compilers to find openssl@1.1 you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"<br>
export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"<br>
For pkg-config to find openssl@1.1 you may need to set:<br>
export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"<br>
==&gt; unbound<br>
To have launchd start unbound now and restart at startup:<br>
sudo brew services start unbound<br>
==&gt; readline<br>
readline is keg-only, which means it was not symlinked into /usr/local,<br>
because macOS provides the BSD libedit library, which shadows libreadline.<br>
In order to prevent conflicts when programs look for libreadline we are<br>
defaulting this GNU Readline installation to keg-only.<br>
For compilers to find readline you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/readline/lib"<br>
export CPPFLAGS="-I/usr/local/opt/readline/include"<br>
For pkg-config to find readline you may need to set:<br>
export PKG_CONFIG_PATH="/usr/local/opt/readline/lib/pkgconfig"<br>
==&gt; sqlite<br>
sqlite is keg-only, which means it was not symlinked into /usr/local,<br>
because macOS provides an older sqlite3.<br>
If you need to have sqlite first in your PATH run:<br>
echo 'export PATH="/usr/local/opt/sqlite/bin:$PATH"' &gt;&gt; ~/.bash_profile<br>
For compilers to find sqlite you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/sqlite/lib"<br>
export CPPFLAGS="-I/usr/local/opt/sqlite/include"<br>
For pkg-config to find sqlite you may need to set:<br>
export PKG_CONFIG_PATH="/usr/local/opt/sqlite/lib/pkgconfig"<br>
==&gt; python<br>
Python has been installed as<br>
/usr/local/bin/python3<br>
Unversioned symlinks <code class="notranslate">python</code>, <code class="notranslate">python-config</code>, <code class="notranslate">pip</code> etc. pointing to<br>
<code class="notranslate">python3</code>, <code class="notranslate">python3-config</code>, <code class="notranslate">pip3</code> etc., respectively, have been installed into<br>
/usr/local/opt/python/libexec/bin<br>
If you need Homebrew's Python 2.7 run<br>
brew install python@2<br>
You can install Python packages with<br>
pip3 install <br>
They will install into the site-package directory<br>
/usr/local/lib/python3.7/site-packages<br>
See: <a href="https://docs.brew.sh/Homebrew-and-Python" rel="nofollow">https://docs.brew.sh/Homebrew-and-Python</a><br>
==&gt; glib<br>
Bash completion has been installed to:<br>
/usr/local/etc/bash_completion.d<br>
==&gt; icu4c<br>
icu4c is keg-only, which means it was not symlinked into /usr/local,<br>
because macOS provides libicucore.dylib (but nothing else).<br>
If you need to have icu4c first in your PATH run:<br>
echo 'export PATH="/usr/local/opt/icu4c/bin:$PATH"' &gt;&gt; ~/.bash_profile<br>
echo 'export PATH="/usr/local/opt/icu4c/sbin:$PATH"' &gt;&gt; ~/.bash_profile<br>
For compilers to find icu4c you may need to set:<br>
export LDFLAGS="-L/usr/local/opt/icu4c/lib"<br>
export CPPFLAGS="-I/usr/local/opt/icu4c/include"<br>
For pkg-config to find icu4c you may need to set:<br>
export PKG_CONFIG_PATH="/usr/local/opt/icu4c/lib/pkgconfig"<br>
==&gt; tesseract<br>
This formula contains only the "eng", "osd", and "snum" language data files.<br>
If you need all the other supported languages, <code class="notranslate">brew install tesseract-lang</code>.</p>
</blockquote>
<p dir="auto">The test code is as follows:</p>
<div class="highlight highlight-source-c++ notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="#import &lt;opencv2/opencv.hpp&gt;
int main(int argc, const char * argv[])
{
    cv::Mat a = cv::Mat::zeros(100, 200, 5);
    cv::Mat b;
    cv::medianBlur(a, b, 5);
}"><pre class="notranslate">#<span class="pl-k">import</span> <span class="pl-s"><span class="pl-pds">&lt;</span>opencv2/opencv.hpp<span class="pl-pds">&gt;</span></span>
<span class="pl-k">int</span> <span class="pl-en">main</span>(<span class="pl-k">int</span> argc, <span class="pl-k">const</span> <span class="pl-k">char</span> * argv[])
{
    cv::Mat a = <span class="pl-c1">cv::Mat::zeros</span>(<span class="pl-c1">100</span>, <span class="pl-c1">200</span>, <span class="pl-c1">5</span>);
    cv::Mat b;
    <span class="pl-c1">cv::medianBlur</span>(a, b, <span class="pl-c1">5</span>);
}</pre></div>
<p dir="auto">The runtime error is "Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)". The program stops at cv::medianBlur(a, b, 5) every time.</p>
<h5 dir="auto">Steps to reproduce</h5>
<ul dir="auto">
<li>homebrew version<br>
Homebrew 2.1.16-89-g2a45343<br>
Homebrew/homebrew-core (git revision 2a800; last commit 2019-11-20)<br>
Homebrew/homebrew-cask (git revision 981f58; last commit 2019-11-20)</li>
<li>opencv4 install<br>
brew install opencv</li>
<li>Test code<br>
As shown above.</li>
</ul>
<h5 dir="auto">System information (version)</h5>
<p dir="auto">Opencv =&gt; 4.0.0 (C++ custom build, includes dnn module)<br>
Operating system =&gt; Ubuntu<br>
Compiler =&gt; GCC</p>
<h5 dir="auto">Detailed description</h5>
<h5 dir="auto">Summary</h5>
<p dir="auto">I have a transfer learning mobilenetV2 classification model, which I want to use in a C++ code using the opencv's cv2 dnn module.</p>
<p dir="auto"><strong>The simplest way -</strong><br>
I have a custom trained mobilenetV2 classification model's frozen inference graph.<br>
From the frozen inference graph, I generated the .pbtxt file using cv2.dnn.writeTextGraph method and ran the prediction using cv2::dnn::readNetFromTensorflow method</p>
<p dir="auto">With just the model file reference alone got the below error.</p>
<blockquote>
<p dir="auto">OpenCV(4.0.0) /home/venkat/OPENCV4/opencv/modules/dnn/src/tensorflow/tf_importer.cpp:497: error: (-2:Unspecified error) Input layer not found: module_apply_default/MobilenetV2/expanded_conv/output in function 'connect'</p>
</blockquote>
<p dir="auto">with both the model file and the config file got the below error.</p>
<blockquote>
<p dir="auto">what():  OpenCV(4.0.0) /home/venkat/OPENCV4/opencv/modules/dnn/src/tensorflow/tf_importer.cpp:616: error: (-215:Assertion failed) const_layers.insert(std::make_pair(name, li)).second in function 'addConstNodes'</p>
</blockquote>
<p dir="auto"><strong>The complex way</strong></p>
<p dir="auto">I followed the instructions mentioned in<br>
<a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="325680712" data-permission-text="Title is private" data-url="https://github.com/opencv/opencv/issues/11577" data-hovercard-type="issue" data-hovercard-url="/opencv/opencv/issues/11577/hovercard?comment_id=391372527&amp;comment_type=issue_comment" href="https://github.com/opencv/opencv/issues/11577#issuecomment-391372527">#11577 (comment)</a><br>
and<br>
<a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="320017992" data-permission-text="Title is private" data-url="https://github.com/opencv/opencv/issues/11452" data-hovercard-type="issue" data-hovercard-url="/opencv/opencv/issues/11452/hovercard" href="https://github.com/opencv/opencv/issues/11452">#11452</a><br>
and<br>
<a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="344960285" data-permission-text="Title is private" data-url="https://github.com/opencv/opencv/issues/12075" data-hovercard-type="issue" data-hovercard-url="/opencv/opencv/issues/12075/hovercard" href="https://github.com/opencv/opencv/issues/12075">#12075</a></p>
<p dir="auto">All the above instructions are typically for the object detection models.<br>
I looked at the <a href="https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_ssd.py">https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_ssd.py</a> which is for mobilenet ssd model.</p>
<p dir="auto">So from various above sources, I ended up creating the below code(in python) for converting the model to be compatible with cv2 dnn</p>
<p dir="auto">with tf.gfile.FastGFile('mobilenet_v2_100_224.pb', 'rb') as f:<br>
graph_def = tf.GraphDef()<br>
graph_def.ParseFromString(f.read())</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="graph_def = optimize_for_inference_lib.optimize_for_inference(graph_def, ['final_retrain_ops/biases/final_biases'], ['final_result'], tf.float32.as_datatype_enum)
graph_def = TransformGraph(graph_def, ['final_retrain_ops/biases/final_biases'], ['final_result'], ['remove_nodes(op=PlaceholderWithDefault)','sort_by_execution_order'])

for i in reversed(range(len(graph_def.node))):
    #code blocks 1
    if graph_def.node[i].op == 'Const':
        del graph_def.node[i]
    #code block 1 ends
    for attr in ['T', 'data_format', 'Tshape', 'N', 'Tidx', 'Tdim',
                'use_cudnn_on_gpu', 'Index', 'Tperm', 'is_training',
                'Tpaddings']:
        if attr in graph_def.node[i].attr:
            print(&quot;Deleting&quot;)
            del graph_def.node[i].attr[attr]
    print(len(graph_def.node))
unconnected_nodes = []
for node in graph_def.node:
    unconnected_nodes.append(node.name)
    for inp in node.input:
        if inp in unconnected_nodes:
            unconnected_nodes.remove(inp)
unconnected_nodes.remove(&quot;final_result&quot;)
for name in unconnected_nodes:
    for i in range(len(graph_def.node)):
        if graph_def.node[i].name == name:
            # print(name)
            del graph_def.node[i]
            break
print(&quot;leftover nodes &quot;)
for node in graph_def.node:
    print(node.name)

with tf.gfile.FastGFile('graph.pb', 'wb') as f:
        f.write(graph_def.SerializeToString())
cv2.dnn.writeTextGraph('graph.pb','graph.pbtxt')"><pre class="notranslate"><code class="notranslate">graph_def = optimize_for_inference_lib.optimize_for_inference(graph_def, ['final_retrain_ops/biases/final_biases'], ['final_result'], tf.float32.as_datatype_enum)
graph_def = TransformGraph(graph_def, ['final_retrain_ops/biases/final_biases'], ['final_result'], ['remove_nodes(op=PlaceholderWithDefault)','sort_by_execution_order'])

for i in reversed(range(len(graph_def.node))):
    #code blocks 1
    if graph_def.node[i].op == 'Const':
        del graph_def.node[i]
    #code block 1 ends
    for attr in ['T', 'data_format', 'Tshape', 'N', 'Tidx', 'Tdim',
                'use_cudnn_on_gpu', 'Index', 'Tperm', 'is_training',
                'Tpaddings']:
        if attr in graph_def.node[i].attr:
            print("Deleting")
            del graph_def.node[i].attr[attr]
    print(len(graph_def.node))
unconnected_nodes = []
for node in graph_def.node:
    unconnected_nodes.append(node.name)
    for inp in node.input:
        if inp in unconnected_nodes:
            unconnected_nodes.remove(inp)
unconnected_nodes.remove("final_result")
for name in unconnected_nodes:
    for i in range(len(graph_def.node)):
        if graph_def.node[i].name == name:
            # print(name)
            del graph_def.node[i]
            break
print("leftover nodes ")
for node in graph_def.node:
    print(node.name)

with tf.gfile.FastGFile('graph.pb', 'wb') as f:
        f.write(graph_def.SerializeToString())
cv2.dnn.writeTextGraph('graph.pb','graph.pbtxt')
</code></pre></div>
<p dir="auto">With the graph.pb and graph.pbtxt when I tried to load the model, I encountered the below error.</p>
<p dir="auto">When I delete the "Const" op nodes (code block 1 in the above code, commented accordingly), I get the following error while writing the text graph.</p>
<blockquote>
<p dir="auto">error: (-215:Assertion failed) nodesMapIt != nodesMap.end() in function 'sortByExecutionOrder'</p>
</blockquote>
<p dir="auto">So I comment the code block 1, so my graph gets generated,<br>
with the below log</p>
<blockquote>
<p dir="auto">...<br>
W1230 17:47:58.718445 139948826896192 optimize_for_inference_lib.py:244] Didn't find expected Conv2D input to 'module_apply_default/MobilenetV2/expanded_conv_16/depthwise/BatchNorm/FusedBatchNorm'<br>
2019-12-30 17:48:00.034702: I tensorflow/tools/graph_transforms/transform_graph.cc:317] Applying remove_nodes<br>
2019-12-30 17:48:00.041844: I tensorflow/tools/graph_transforms/transform_graph.cc:317] Applying sort_by_execution_order</p>
</blockquote>
<p dir="auto">and with the generated graph, when I tried to load in cv2 dnn module, ended up at this error.</p>
<blockquote>
<p dir="auto">error: (-215:Assertion failed) const_layers.insert(std::make_pair(name, li)).second in function 'addConstNodes'</p>
</blockquote>
<p dir="auto">I also tried using the <a href="https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_common.py">https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_common.py</a> file to convert, still, I ended up in errors.</p>
<p dir="auto">Would like to know more on this issue, and the proper way to convert a custom trained mobile net v2 classification model compatible for opencv dnn module.</p>