如何在OpenCV中导入具有展平图层的TensorFlow模型?

时间:2018-01-06 12:06:54

标签: c++ opencv tensorflow keras

我用Keras创建了一个CNN。网的代码是:

model = Sequential()

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

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

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

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid', name='result_class'))

然后,使用this script,我在.pb中转换了由Keras创建的.h5文件。

现在我想使用OpenCV(3.4)导入模型,但是当我执行以下代码时

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;
    }
}

我收到此错误:

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

似乎OpenCV无法处理展平层,对不对?有没有办法导入我的网?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

是的,现在看起来Opencv在处理展平图层时遇到问题。 您可以在此处查看更多相关信息:https://github.com/opencv/opencv_contrib/issues/1241

解决方法建议在网络上直接使用tf.reshape。但我也正在研究如何在keras层上做到这一点。