# cv::error: (-2:未指定错误) 解析 ONNX 模型失败: (节点: 'Gemm_0') 输入张量 'A' 有 3 维但预期 2 维 在函数 'cv::dnn::dnn4_v20231225::ONNXImporter::parseNode' 中

- **ID:** `opencv/dnn-readnet-from-onnx-failed`
- **领域:** opencv
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

ONNX 模型包含一个 Gemm（通用矩阵乘法）节点，该节点期望 2D 输入，但实际输入张量有 3 维，通常是由于批次维度不匹配或模型导出错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| opencv-4.8.0 | active | — | — |
| opencv-4.9.0 | active | — | — |
| opencv-4.10.0 | active | — | — |

## 解决方案

1. ```
   Use ONNX Runtime (onnxruntime) to validate and fix the model: run 'python -c "import onnx; model = onnx.load('model.onnx'); onnx.checker.check_model(model)"'. If the model is valid, try simplifying it with onnx-simplifier: 'python -m onnxsim model.onnx simplified.onnx'. Then load simplified.onnx with OpenCV.
   ```
2. ```
   Export the model from PyTorch with torch.onnx.export(model, dummy_input, 'model.onnx', opset_version=11, input_names=['input'], output_names=['output'], dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}). Ensure the model uses only supported operators by setting opset_version <= 12.
   ```
3. ```
   Manually edit the ONNX graph using onnx_graphsurgeon: remove the problematic Gemm node and replace with MatMul + Add. Example: import onnx_graphsurgeon as gs; graph = gs.import_onnx(onnx.load('model.onnx')); for node in graph.nodes: if node.op == 'Gemm': node.op = 'MatMul'; # adjust inputs/outputs; onnx.save(gs.export_onnx(graph), 'fixed.onnx')
   ```

## 无效尝试

- **Reinstall OpenCV with ONNX support enabled via -DWITH_ONNX=ON** — The error is a parsing issue with the model structure, not a missing module. OpenCV's DNN module already supports ONNX by default. (95% 失败率)
- **Convert the model to TensorFlow protobuf format and load with readNetFromTensorflow** — The underlying layer structure issue (Gemm with wrong tensor shape) will likely persist after conversion, or the conversion itself may fail. (70% 失败率)
- **Set the input blob with a different shape using blobFromImage with size 224x224** — The error is at model parsing time, before any forward pass. Changing input blob shape doesn't affect model structure parsing. (90% 失败率)
