OpenCV:无法创建层"flatten_1/Shape"类型为“形状"的 [英] OpenCV: Can't create layer "flatten_1/Shape" of type "Shape"

查看:127
本文介绍了OpenCV:无法创建层"flatten_1/Shape"类型为“形状"的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在opencv dnn中实现一个Tensorflow模型.这是我遇到的错误:

I've tried to implement a tensorflow model in opencv dnn. This is the error I've got:

OpenCV:无法创建类型为"Shape"的图层"flatten_1/Shape"

OpenCV: Can't create layer "flatten_1/Shape" of type "Shape"

我用keras来建立模型

I used keras to build my model

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape = (32,32,1), activation = 'relu'))

model.add(Conv2D(32, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())#<== this is the layer that opencv doesnt support

model.add(Dense(units = 128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(units = num_classes, activation = 'softmax'))

我已经尝试过:

from tensorflow.python.keras.layers.core import Reshape

model.add(Reshape((-1,)))

但是它又给出了另一个错误

But it gave another error

TypeError:添加的图层必须是类Layer的实例.找到:tensorflow.python.keras.layers.core.Reshape对象位于0x000001D21EF1A630>

TypeError: The added layer must be an instance of class Layer. Found: tensorflow.python.keras.layers.core.Reshape object at 0x000001D21EF1A630>

从那里我还没有找到任何解决方案.我的问题是在keras中是否可以替换Flatten().

From there I didn't find any solution yet. My question is that is there any replacement for Flatten() in keras.

推荐答案

我发现OpenCV dnn仅允许推理,因此需要对模型进行优化以进行推理.我使用来自tensorflow的图变换工具来做到这一点.

I found that OpenCV dnn only allow inference, so the model need to be optimized for inference. I use graph transform tool from tensorflow to do that.

from tensorflow.tools.graph_transforms import TransformGraph

graph = TransformGraph(graph,
            ["input_1"], # inputs nodes
            ["dense_2/Softmax"], # outputs nodes
            ['fold_constants()',
            'strip_unused_nodes(type=float, shape="None,32,32,1")',
            'remove_nodes(op=Identity, op=CheckNumerics)',
            'fold_batch_norms',
            'fold_old_batch_norms'
            ])

这篇关于OpenCV:无法创建层"flatten_1/Shape"类型为“形状"的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆