首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >tensorflow教程中的Show_inference错误

tensorflow教程中的Show_inference错误
EN

Stack Overflow用户
提问于 2022-09-23 14:34:12
回答 2查看 45关注 0票数 -2

我对python和tensorflow完全陌生。同时在模范动物园学习本教程。我遇到了show_inference错误。请解释一下它的意思以及如何修复它。我搜索堆栈溢出并撞向这个线程感应器实现过程中的误差--流对象检测模型,但错误似乎与我遇到的不同。

代码语言:javascript
运行
复制
!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)

如下所示的错误

代码语言:javascript
运行
复制
<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:
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-23 17:45:25

试着安装

代码语言:javascript
运行
复制
python -m ensurepip --default-pip
python -m pip install

new version !pip install -U --pre tensorflow=="2.4.1"

票数 0
EN

Stack Overflow用户

发布于 2022-09-23 16:49:50

我将tensorflow版本更改为2.4.1,使用了!pip安装-U --pre tensorflow=="2.4.1“,它解决了这个问题。

图像结果

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73829340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档