-2 opencv module_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
1Evidence
2024-06-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.8.0 active
4.9.0 active
4.10.0 active

Root Cause

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

generic

中文

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

Official Documentation

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

Workarounds

  1. 80% success # 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)
    # 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. 75% success net = cv2.dnn.readNetFromTensorflow('model.pb', 'model.pbtxt') # Provide text protobuf for graph structure
    net = cv2.dnn.readNetFromTensorflow('model.pb', 'model.pbtxt')  # Provide text protobuf for graph structure

中文步骤

  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

Dead Ends

Common approaches that don't work:

  1. 50% fail

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

  2. 70% fail

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

  3. 60% fail

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