tensorflow / models

Models and examples built with TensorFlow
Other
77.05k stars 45.77k forks source link

'AutoTrackable' object has no attribute 'output_shapes' #9304

Closed YuByoungJoon closed 3 years ago

YuByoungJoon commented 4 years ago

I use python3.6 and tensorflow 2.3.0

I want playing object_detection DEMO

but last "masking_model.output_shapes" is make error I don't know How to change python code...?

!pip3 install -U --pre tensorflow=="2.*" !pip3 install tf_slim !pip install pycocotools

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

%%bash cd models/research/ protoc object_detection/protos/*.proto --python_out=.

%%bash cd models/researchls 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

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

patch tf1 into utils.ops

utils_ops.tf = tf.compat.v1

Patch the location of gfile

tf.gfile = tf.io.gfile

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

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)

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

model_name = 'ssd_mobilenet_v1_coco_2017_11_17' detection_model = load_model(model_name)

print(detection_model.signatures['serving_default'].inputs)

detection_model.signatures['serving_default'].output_dtypes

detection_model.signatures['serving_default'].output_shapes 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:

`!pip3 install -U --pre tensorflow=="2.*" !pip3 install tf_slim !pip install pycocotools

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

%%bash cd models/research/ protoc object_detection/protos/*.proto --python_out=.

%%bash cd models/researchls 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

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

patch tf1 into utils.ops

utils_ops.tf = tf.compat.v1

Patch the location of gfile

tf.gfile = tf.io.gfile

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

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)

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

model_name = 'ssd_mobilenet_v1_coco_2017_11_17' detection_model = load_model(model_name)

print(detection_model.signatures['serving_default'].inputs)

detection_model.signatures['serving_default'].output_dtypes

detection_model.signatures['serving_default'].output_shapes 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

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)

model_name = "mask_rcnn_inception_resnet_v2_atrous_coco_2018_01_28" masking_model = load_model(model_name)`

It went so well so far. masking_model.output_shape

AttributeError Traceback (most recent call last) in ----> 1 masking_model.output_shapes

AttributeError: 'AutoTrackable' object has no attribute 'output_shapes'

I don't know what the'AutoTrackable' object has no attribute'output_shapes' should fix. plz help me....

ravikyram commented 4 years ago

@YuByoungJoon

Looks like duplicate if #9236 . Can we close the issue here and track the issue in #9236.Please, confirm. Thanks!

YuByoungJoon commented 4 years ago

Thank you for your kind. I succeeded thanks. I use code == masking_model.signatures['serving_default'].output_shapes

but next step error

like this

for image_path in TEST_IMAGE_PATHS: show_inference(masking_model, image_path)

TypeError Traceback (most recent call last)

in 1 for image_path in TEST_IMAGE_PATHS: ----> 2 show_inference(masking_model, image_path) 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( in run_inference_for_single_image(model, image) 26 detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( 27 output_dict['detection_masks'], output_dict['detection_boxes'], ---> 28 image.shape[0], image.shape[1]) 29 detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5, 30 tf.uint8) C:\models\research\object_detection\utils\ops.py in reframe_box_masks_to_image_masks(box_masks, boxes, image_height, image_width, resize_method) 823 as `box_masks`. 824 """ --> 825 resize_method = 'nearest' if box_masks.dtype == tf.uint8 else resize_method 826 # TODO(rathodv): Make this a public function. 827 def reframe_box_masks_to_image_masks_default(): TypeError: data type not understood why..? I am following the example but finally got an error.
SkyWriter commented 3 years ago

@YuByoungJoon you can review https://github.com/tensorflow/models/pull/9430 to see what changes are required to make your code work. Just in case it's still relevant.

google-ml-butler[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you.

google-ml-butler[bot] commented 3 years ago

Closing as stale. Please reopen if you'd like to work on this further.

google-ml-butler[bot] commented 3 years ago

Are you satisfied with the resolution of your issue? Yes No

araby123 commented 2 years ago

I have same issue but in input

this error : AttributeError: 'AutoTrackable' object has no attribute 'inputs'

any help : https://stackoverflow.com/questions/71193600/issue-to-make-tts-model-from-pb-file-to-tflight-attributeerror-autotrackable