Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How to import TensorFlow model with flatten layer?

Hello everybody,

I have created a CNN with Keras. The code of the net is:

model = Sequential()

model.add(Conv2D(32, (3,3), data_format='channels_last', input_shape=(48, 32, 3), name='data'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Activation('sigmoid', name='result_class'))

Then, using this script, I have converted the .h5 file, created by Keras, in .pb.

Now I want to import the model using OpenCV (3.3), but when I execute the following code

Net net;
try {
    net = dnn::readNetFromTensorflow(model_path);
catch (cv::Exception& e) {
    cerr << "Exception: " << e.what() << endl;
    if (net.empty()) {
        cerr << "Can't load the model" << endl;

I get this error:

OpenCV Error: Unspecified error (Unknown layer type Shape in op flatten_1/Shape) in populateNet, file /home/nicola/Scrivania/opencv-3.4.0/opencv-3.4.0/modules/dnn/src/tensorflow/tf_importer.cpp, line 1487
Exception: /home/nicola/Scrivania/opencv-3.4.0/opencv-3.4.0/modules/dnn/src/tensorflow/tf_importer.cpp:1487: error: (-2) Unknown layer type Shape in op flatten_1/Shape in function populateNet
Can't load the model

It seems that OpenCV can't handle flatten layer, am I right? Is there a way to import my net?

Thanks for your help.