2023年11月29日发(作者:)
opencv调⽤Onnx模型常见问题
以下都是pytorch模型转换为onnx,然后利⽤opencv中dnn模块的readNetFromONNX()函数调⽤后出现的⼀些问题, 利⽤onnxruntime库已经验证onnx结果正确。
相关环境
python: 3.7.4
torch: 1.5.0
onnx: 1.10.2
onnxruntime: 1.9.0
⼀、permute_:138: error: (-215:Assertion failed) (int)_numAxes == inputs[0].size()
出错原因
opencv版本:4.5.3
在⽹络结构中有⼀层是对三维数据进⾏维度变换,⽬前好像不⽀持。详细代码可以参考提的issue
res = e(0, 2, 1) # xyz==> (B, N, C)
参考说的好像是当前python-opencv会⾃动把三维输⼊的第三维转换为彩图的通道数。
尝试解决办法
考虑先⽤或者增加⼀个维度,操作完再⽤或者变换为原来的维度。
eze(0)e(0)
有兴趣的可参考尝试其他⽅法
⼆、Unspecified error: Can't create layer "layer_name" of type "Cast" in function getLayerInstance
出错原因
opencv版本:4.2.0
不⽀持算⼦
Cast
解决办法
升级opencv版本4.3.0以上
⾃定义算⼦ 参考/4.x/dc/db1/tutorial_dnn_custom_
三、Unspecified error: Can't create layer "82" of type "ConstantOfShape" in function 'getLayerInstance'
出错原因
opencv版本:4.2.0
不⽀持算⼦
ConstantOfShape
解决办法
升级opencv版本4.3.0以上
⾃定义算⼦ 参考/4.x/dc/db1/tutorial_dnn_custom_
四、onnx_:2146: error: (-2:Unspecified error)
完整错误
: OpenCV(4.5.3) C:UsersrunneradminAppDataLocalTemppip-req-build-c2l3r8zmopencvmodulesdnnsrconnxonnx_:2146: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20210608::ONNXImporter::handleNode'
> Node [ConstantOfShape]:(203) parse error: OpenCV(4.5.3) C:UsersrunneradminAppDataLocalTemppip-req-build-c2l3r8zmopencvmodulesdnnsrconnxonnx_:1833: error: (-2:Unspecified error) in function 'void __cdecl cv::dnn:
> > (expected: 'inpShape[i] > 0'), where
> > 'inpShape[i]' is 0
> > must be greater than
> > '0' is 0
>
出错原因
opencv版本:4.5.3
在⽹络结构中有⼀层是根据已有维度B,C⽣成⼀个相同维度的全零tensor, 调⽤的时候shape返回的是tensor,
B, N, C = (B, C, dtype=, device=device)
在⽣成的时候本来应该传⼊int,这⾥会导致错误。
解决办法
把维度数加上int(), 强制转换为int整数。
(int(B), int(C), dtype=, device=device)
五、Unspecified error: Can't create layer "82" of type "ArgMax" in function 'getLayerInstance'
出错原因
opencv版本:4.5.3
不⽀持算⼦
ArgMax
解决办法
⾃定义算⼦ 参考/4.x/dc/db1/tutorial_dnn_custom_
class ArgMaxLayer(object):
def __init__(self, params, blobs):
print("params: ", params)
= params["axis"]
= None
# Our layer receives one inputs. We need to find the max
def getMemoryShapes(self, inputs):
input_dim = inputs[0]
for i in range(len(input_dim)):
if i != :
out_(input_dim[i])
= out_dim
return [out_dim]
def forward(self, inputs):
data = inputs[0]
print("inputs-: ", type(data), )
print("axis: ", )
res = (data, axis=)
# shape =
# print("shape: ", shape)
# res = t(0, shape[], tuple(), dtype=ng)
print(res, , )
return [(32)]
_registerLayer('ArgMax', ArgMaxLayer)
参考官⽹最新修改, ,⾃⼰重新编译⽣成opencv
六、error: (-215:Assertion failed) pyOutputs[i].size == outputs[i].size in function 'pycvLayer::forward'
我⾃定义算⼦时出现过这种情况,⾸先检查⾃定义层中函数返回值的维度是否和中⼀致, 则检查下是否遇到以下巨坑:
forwardgetMemoryShapes
检查输出维度是否为3维,如果是则可以先把输出(输⼊)升维,外部调⽤获取结果后再降维。
七、error: (-215:Assertion failed) pyOutputs[i].type() == outputs[i].type() in function 'pycvLayer::forward'


发布评论