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

TensorFlow Model Zoo教程show_inference报错原因及解决方法

TensorFlow Model Zoo推理报错的问题排查与修复

问题描述

作为Python和TensorFlow完全新手,在遵循TensorFlow Model Zoo教程操作时,调用show_inference函数出现错误。执行代码及报错信息如下:

执行代码

!pip install -U --pre tensorflow=="2.*"
!pip install tf_slim
#Make sure you have pycocotools installed

!pip install pycocotools
#Get tensorflow/models or cd to parent directory of the repository.

import os
import pathlib


if "models" in pathlib.Path.cwd().parts:
  while "models" in pathlib.Path.cwd().parts:
    os.chdir('..')
elif not pathlib.Path('models').exists():
  !git clone --depth 1 https://github.com/tensorflow/models
#Compile protobufs and install the object_detection package

%%bash
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
%%bash 
cd models/research
cp object_detection/packages/tf2/setup.py .
pip install .

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display
# Import the object detection module.

from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# Patches:

# patch tf1 into `utils.ops`
utils_ops.tf = tf.compat.v1

# Patch the location of gfile
tf.gfile = tf.io.gfile
# Model preparation
# Variables
# Any model exported using the export_inference_graph.py tool can be loaded here simply by changing the path.

# By default we use an "SSD with Mobilenet" model here. See the detection model zoo for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# Loader
def load_model(model_name):
  base_url = 'http://download.tensorflow.org/models/object_detection/'
  model_file = model_name + '.tar.gz'
  model_dir = tf.keras.utils.get_file(
    fname=model_name, 
    origin=base_url + model_file,
    untar=True)

  model_dir = pathlib.Path(model_dir)/"saved_model"

  model = tf.saved_model.load(str(model_dir))

  return model
# Loading label map
# Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'models/research/object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
# For the sake of simplicity we will test on 2 images:

# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = pathlib.Path('models/research/object_detection/test_images')
TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob("*.jpg")))
TEST_IMAGE_PATHS
# Detection
# Load an object detection model:

model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
detection_model = load_model(model_name)
# Check the model's input signature, it expects a batch of 3-color images of type uint8:

print(detection_model.signatures['serving_default'].inputs)
# And returns several outputs:

detection_model.signatures['serving_default'].output_dtypes
detection_model.signatures['serving_default'].output_shapes
# Add a wrapper function to call the model, and cleanup the outputs:

def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

  # Run inference
  model_fn = model.signatures['serving_default']
  output_dict = model_fn(input_tensor)

  # All outputs are batches tensors.
  # Convert to numpy arrays, and take index [0] to remove the batch dimension.
  # We're only interested in the first num_detections.
  num_detections = int(output_dict.pop('num_detections'))
  output_dict = {key:value[0, :num_detections].numpy() 
                 for key,value in output_dict.items()}
  output_dict['num_detections'] = num_detections

  # detection_classes should be ints.
  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
   
  # Handle models with masks:
  if 'detection_masks' in output_dict:
    # Reframe the the bbox mask to the image size.
    detection_masks_reframed = utils_ops.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
# Run it on each test image and show the results:

def show_inference(model, image_path):
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = np.array(Image.open(image_path))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=8)

  display(Image.fromarray(image_np))
for image_path in TEST_IMAGE_PATHS:
  show_inference(detection_model, image_path)

报错信息

<ipython-input-76-c689a76e14bc> in <module>
      1 for image_path in TEST_IMAGE_PATHS:
      2   print(image_path)
----> 3   show_inference(detection_model, image_path)

8 frames
<ipython-input-69-e474e557b383> in show_inference(model, image_path)
      4   image_np = np.array(Image.open(image_path))
      5   # Actual detection.
----> 6   output_dict = run_inference_for_single_image(model, image_np)
      7   # Visualization of the results of a detection.
      8   vis_util.visualize_boxes_and_labels_on_image_array(

<ipython-input-41-f78bdbc8caa5> in run_inference_for_single_image(model, image)
      8   # Run inference
      9   model_fn = model.signatures['serving_default']
---> 10   output_dict = model_fn(input_tensor)
     11 
     12   # All outputs are batches tensors.

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
   1602       TypeError: If the arguments do not match the function's signature.
   1603     """
-> 1604     return self._call_impl(args, kwargs)
   1605 
   1606   def _call_impl(self, args, kwargs, cancellation_manager=None):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/wrap_function.py in _call_impl(self, args, kwargs, cancellation_manager)
    242     else:
    243       return super(WrappedFunction, self)._call_impl(
-> 244           args, kwargs, cancellation_manager)
    245 
    246   def prune(self, feeds, fetches, name=None, input_signature=None):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _call_impl(self, args, kwargs, cancellation_manager)
   1620             raise structured_err
   1621 
-> 1622       return self._call_with_flat_signature(args, kwargs, cancellation_manager)
   1623 
   1624   def _call_with_flat_signature(self, args, kwargs, cancellation_manager):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _call_with_flat_signature(self, args, kwargs, cancellation_manager)
   1669                         f"#{i}(zero-based) to be a Tensor; "
   1670                         f"got {type(arg).__name__} ({arg}).")
-> 1671     return self._call_flat(args, self.captured_inputs, cancellation_manager)
   1672 
   1673   def _call_with_structured_signature(self, args, kwargs, cancellation_manager):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1861       # No tape is watching; skip to running the function.
   1862       return self._build_call_outputs(self._inference_function.call(
-> 1863           ctx, args, cancellation_manager=cancellation_manager))
   1864     forward_backward = self._select_forward_and_backward_functions(
   1865         args,

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in call(self, ctx, args, cancellation_manager)
    502               inputs=args,
    503               attrs=attrs,
-> 504               ctx=ctx)
    505         else:
    506           outputs = execute.execute_with_cancellation(

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     53     ctx.ensure_initialized()
     54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
-> 55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:
     57     if name is not None:

错误原因解释

从报错栈可以看出,问题核心是模型推理调用时输入张量与模型期望的格式不匹配,或环境版本兼容问题导致模型加载/执行失败:

  • 输入图像可能是单通道灰度图,但模型要求3通道RGB格式
  • 输入张量的数据类型不符合模型要求(模型标注需要uint8,但实际传入的可能是其他类型)
  • TensorFlow版本与models仓库版本不兼容,导致模型加载后无法正常执行

修复方法

1. 确保输入图像为RGB格式

修改show_inference函数中读取图像的代码,强制转换为RGB通道:

def show_inference(model, image_path):
  # 强制转换为RGB格式,避免灰度图(单通道)导致的维度不匹配
  image_np = np.array(Image.open(image_path).convert("RGB"))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=8)

  display(Image.fromarray(image_np))

2. 明确指定输入张量的数据类型

在run_inference_for_single_image函数中,转换张量时指定dtype=tf.uint8,确保和模型要求一致:

def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # 明确指定张量类型为uint8,匹配模型输入要求
  input_tensor = tf.convert_to_tensor(image, dtype=tf.uint8)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

  # Run inference
  model_fn = model.signatures['serving_default']
  output_dict = model_fn(input_tensor)

  # 后续代码保持不变...

3. 确保TensorFlow与models仓库版本兼容

TensorFlow 2.x不同版本和models仓库的分支兼容性差异较大,建议指定匹配的版本:

  • 安装指定版本的TensorFlow:
!pip install tensorflow==2.11.0
  • 克隆对应分支的models仓库:
!git clone --depth 1 --branch r2.11 https://github.com/tensorflow/models

然后重新执行protobuf编译和package安装步骤。

4. 验证模型加载完整性

如果上述方法无效,可以尝试重新下载模型,确保模型文件未损坏:

def load_model(model_name):
  base_url = 'http://download.tensorflow.org/models/object_detection/'
  model_file = model_name + '.tar.gz'
  # 删除已下载的模型文件,重新下载
  model_dir = tf.keras.utils.get_file(
    fname=model_name, 
    origin=base_url + model_file,
    untar=True,
    cache_subdir='models',
    cache_dir='./',
    force_download=True)

  model_dir = pathlib.Path(model_dir)/"saved_model"

  model = tf.saved_model.load(str(model_dir))

  return model

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:30:30