You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow目标检测API运行报错求助:TypeError类型转换问题

Troubleshooting TensorFlow Object Detection API Tutorial Issues in TF2.2.0

Hey there! Let's work through the problems you're facing with the Object Detection API tutorial. These issues usually stem from compatibility gaps between older TF1-style models and TF2's execution model, so let's break this down step by step.

Root Cause Analysis

The warnings and errors you're seeing are linked:

  • The tensorflow:Saver not created because there are no variables in the graph to restore message happens because you're loading a TF1 checkpoint-style model with TF2's load_model function, which expects a TF2 SavedModel format.
  • The TypeError: int() argument must be a string... not 'Tensor' error occurs because the model is returning unevaluated tensors instead of computed values—this is a sign the model isn't being executed in TF2's eager mode correctly.

Step-by-Step Fixes

1. Switch to a TF2-Compatible Model

Old models like ssd_mobilenet_v1_coco_2017_11_17 are built for TF1 and don't play nicely with TF2's eager execution. Instead, use a TF2-native model from the TensorFlow Model Zoo (no external link needed—just search for TF2 models). A good starting point is:
ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8

2. Load the Model Correctly for TF2

Replace your current model loading code with TF2's tf.saved_model.load() (designed for SavedModel formats) instead of load_model (which is for Keras models):

import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
import pathlib

# Path to your downloaded TF2 model
model_name = 'ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8'
model_dir = pathlib.Path('models/research/object_detection/test_data') / model_name
loaded_model = tf.saved_model.load(str(model_dir))
# Get the serving signature for inference
detection_model = loaded_model.signatures['serving_default']

3. Update the Inference Function to Handle TF2 Tensors

Modify the run_inference_for_single_image function to evaluate tensors to numpy values (since TF2 returns tensors by default):

def run_inference_for_single_image(model, image):
    image = np.asarray(image)
    # Convert to tensor and add batch dimension
    input_tensor = tf.convert_to_tensor(image)
    input_tensor = input_tensor[tf.newaxis, ...]

    # Run inference (returns tensor outputs)
    output_dict = model(input_tensor)

    # Convert tensors to numpy arrays and remove batch dimension
    num_detections = int(output_dict.pop('num_detections')[0].numpy())
    output_dict = {key: value[0, :num_detections].numpy()
                   for key, value in output_dict.items()}
    output_dict['num_detections'] = num_detections

    # Convert detection classes to integers
    output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)

    # Handle mask outputs if present
    if 'detection_masks' in output_dict:
        detection_masks_reframed = viz_utils.reframe_box_masks_to_image_masks(
            output_dict['detection_masks'], output_dict['detection_boxes'],
            image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5, tf.uint8)
        output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()

    return output_dict

4. Verify Your Environment Setup

Double-check these critical setup steps to avoid hidden issues:

  • Ensure you're using the TF2 branch of the TensorFlow Models repo (not the old TF1 branch).
  • Recompile protobufs to make sure they're TF2-compatible:
    cd models/research
    protoc object_detection/protos/*.proto --python_out=.
    
  • Confirm models/research and models/research/slim are added to your PYTHONPATH:
    export PYTHONPATH=$PYTHONPATH:/path/to/your/models/research:/path/to/your/models/research/slim
    

5. Re-Download the Model (If Needed)

Corrupted model files can cause weird loading issues. Delete the old model directory and re-download the TF2 model from the Model Zoo to rule this out.

Final Notes

Once you make these changes, your inference loop should work as expected—each image will run through the model and return computed detection values instead of unevaluated tensors. If you still hit snags, try starting fresh with the official TF2 Object Detection tutorial code (it's optimized for TF2.x and avoids these compatibility pitfalls).

内容的提问来源于stack exchange,提问作者Kundan Jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:03:12