-2 opencv module_error ai_generated true

cv2.error: OpenCV(4.8.0) /modules/dnn/src/tensorflow/tf_io.cpp:89: error: (-2:未指定错误) 无法读取 .pb 文件:无效的 GraphDef

cv2.error: OpenCV(4.8.0) /modules/dnn/src/tensorflow/tf_io.cpp:89: error: (-2:Unspecified error) FAILED to read .pb file: Invalid GraphDef

ID: opencv/dnn-readnet-from-tensorflow-failed

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
1证据数
2024-06-20首次发现

版本兼容性

版本状态引入弃用备注
4.8.0 active
4.9.0 active
4.10.0 active

根因分析

TensorFlow .pb 模型文件损坏、与 OpenCV 的 protobuf 版本不兼容,或使用不同的操作集导出。

English

The TensorFlow .pb model file is corrupted, incompatible with OpenCV's protobuf version, or exported with a different opset.

generic

官方文档

https://docs.opencv.org/4.x/d6/d0f/group__dnn.html

解决方案

  1. # In TensorFlow:
    import tensorflow as tf
    from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
    # Freeze and save as frozen graph
    model = tf.saved_model.load('model_dir')
    frozen_func = convert_variables_to_constants_v2(model.signatures['serving_default'])
    tf.io.write_graph(frozen_func.graph, '.', 'frozen_model.pb', as_text=False)
  2. net = cv2.dnn.readNetFromTensorflow('model.pb', 'model.pbtxt')  # Provide text protobuf for graph structure

无效尝试

常见但无效的做法:

  1. 50% 失败

    If the model was exported with an incompatible TensorFlow version, re-downloading won't change the GraphDef format.

  2. 70% 失败

    ONNX conversion may fail if the original GraphDef is malformed or contains unsupported operations.

  3. 60% 失败

    OpenCV's bundled protobuf may still be incompatible with newer TensorFlow exports; the error persists.