mardi 19 octobre 2021

Load frozen graph in OpenCV DNN C++

I get the following error while loading a frozen graph in C++ using the given code. What am I doing wrong? Please help me to solve this problem.

terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.1.0) /home/Downloads/opencv-4.1.0/modules/dnn/src/tensorflow/tf_graph_simplifier.cpp:860: error: (-215:Assertion failed) nodesMapIt != nodesMap.end() in function 'sortByExecutionOrder'

Aborted (core dumped)

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/dnn/dnn.hpp>

using namespace std;
using namespace cv;
using namespace dnn;

int main()
{
    // load the neural network model
    cv::dnn::Net inputNet;
    inputNet = cv::dnn::readNet("frozen_graph.pb");
    //inputNet = cv::dnn::readNetFromTensorflow("frozen_graph.pb");
}

I got the frozen_graph.pb using the following conversion in python and tensorflow 2.4

import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2

loaded = tf.saved_model.load('savedmodel')
infer = loaded.signatures['serving_default']

f = tf.function(infer).get_concrete_function(input_1=tf.TensorSpec(shape=[None, 160, 160, 3], dtype=tf.float32))
f2 = convert_variables_to_constants_v2(f)
graph_def = f2.graph.as_graph_def()

# write frozen graph (single file) to disk
with tf.io.gfile.GFile('frozen_graph.pb', 'wb') as f:
   f.write(graph_def.SerializeToString())

and I can successfully use it with the following code in python

import cv2
import numpy as np
img = cv2.imread(r"1.jpg")
net = cv2.dnn.readNet('frozen_graph.pb')
imgn = imgn.astype(np.float32)
# create blob from image (opencv dnn way of pre-processing)
input_blob = cv2.dnn.blobFromImage(imgn, 1, (160,160), 0, swapRB=False, crop=False)
net.setInput(input_blob)
feature_vector_dnn = net.forward()

These questions are related but can't help.

Aucun commentaire:

Enregistrer un commentaire