我试图在opencv dnn中实现一个Tensorflow模型。这是我遇到的错误:
OpenCV:无法创建“形状”类型的图层“ flatten_1 / Shape”
我用keras来建立模型
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'))
我已经尝试过this:
from tensorflow.python.keras.layers.core import Reshape
model.add(Reshape((-1,)))
但是它又给出了另一个错误
TypeError:添加的图层必须是类Layer的实例。找到:tensorflow.python.keras.layers.core.Reshape对象位于0x000001D21EF1A630>
从那里我还没有找到任何解决方案。我的问题是,在喀拉拉邦Flatten()
有什么替代品吗?
答案 0 :(得分:1)
尝试将“展平”更改为以下内容:
#model.add(Flatten())
a, b, c, d = model.output_shape
a = b * c * d
model.add(Permute([1, 2, 3])) # Indicate NHWC data layout
model.add(Reshape((a,)))
答案 1 :(得分:0)
我发现OpenCV dnn仅允许推理,因此需要对模型进行优化以进行推理。我使用来自tensorflow的图变换工具来做到这一点。
import tensorflow.tools.graph_transforms as graph_transforms
graph = graph_transforms.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'
]