Error on interpreter.get_tensor(output_details

Hello,
I’m using:

  • python 2.5.3
  • tensorflow 2.3.0

What error am I making?

Thanks!

import tensorflow as tf
import numpy as np
import cv2
from PIL import Image

interpreter = tf.lite.Interpreter(model_path="mobilenet_v1_1.0_224_quant.tflite", num_threads=None)
#model_path="model.tflite", num_threads=None)

interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()


input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# check the type of the input tensor
floating_model = input_details[0]['dtype'] == np.float32
  
# NxHxWxC, H:1, W:2
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
img = Image.open("test.jpg").resize((width, height))
# add N dim
input_data = np.expand_dims(img, axis=0)
if floating_model:
  input_data = (np.float32(input_data) - 127.5) / 127.5

interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

print(interpreter.get_tensor(output_details[0]['index']))
print(interpreter.get_tensor(output_details[1]['index']))
print(interpreter.get_tensor(output_details[2]['index']))
print(interpreter.get_tensor(output_details[3]['index']))

Error:
print(interpreter.get_tensor(output_details[1][‘index’]))
IndexError: list index out of range

Hi @Marcelo_Aragao

First of all print the whole output details to see the shape and if it has ‘index’ info inside.

1 Like

Thank you George!

Sorry! I am migrating from other technologies and am not yet familiar with TF.
Could you show me the way to get these values?

Thanks!

What

print(output_details)

gives you?

Thanks George!

Follow result:

[{‘index’: 87, ‘quantization’: (0.00390625, 0), ‘sparsity_parameters’: {}, ‘quantization_parameters’: {‘zero_points’: array([0]), ‘scales’: array([0.00390625], dtype=float32), ‘quantized_dimension’: 0}, ‘name’: ‘MobilenetV1/Predictions/Reshape_1’, ‘dtype’: <class ‘numpy.uint8’>, ‘shape’: array([ 1, 1001]), ‘shape_signature’: array([ 1, 1001])}]

Hi,

So do it like:

output_data = interpreter.get_tensor(output_details[0][‘index’])
print(output_data)

there is no output_details[1]['index']) , so it throws an error.

Best

Dear George,
Thank you so much!

I’m trying to count the total number of occurrences of the same index above 0.5 for example.
" Interpreter.get_tensor(output_details" can you give me this value?

Thanks,
Marcelo

I do not understand this. PLease check the official documentation for inference.

I’ve already checked and couldn’t understand how to get the total number of occurrences of an object present in an image.
Thanks! I think I will go back to using what I used.
Once again thanks for the help.

1 Like

I had read this documentation and read it again now that you indicated it, but I couldn’t solve my problem.
My application is very simple: Count the number of objects in an image (jpg). Example: counting the number of people in an image.
I have a Python/Tflite program that can detect only one person even though there are three people in the image.

Could you indicate something like that?

Thanks!

I cleaned up my code to make it easier to read.

Result:
2 0.91796875 ← it’s ok but the image has 3 people and i need that total.

import numpy as np
import cv2

from PIL import Image
from tflite_runtime.interpreter import Interpreter

def load_labels(path):
  with open(path, 'r') as f:
    return {i: line.strip() for i, line in enumerate(f.readlines())}

def set_input_tensor(interpreter, image):
  tensor_index = interpreter.get_input_details()[0]['index']
  input_tensor = interpreter.tensor(tensor_index)()[0]
  input_tensor[:, :] = image

def classify_image(interpreter, image, top_k=1):
  """Returns a sorted array of classification results."""
  set_input_tensor(interpreter, image)
  interpreter.invoke()
  output_details = interpreter.get_output_details()[0]
  output = np.squeeze(interpreter.get_tensor(output_details['index']))

  # If the model is quantized (uint8 data), then dequantize the results
  if output_details['dtype'] == np.uint8:
    scale, zero_point = output_details['quantization']
    output = scale * (output - zero_point)

  ordered = np.argpartition(-output, top_k)
  return [(i, output[i]) for i in ordered[:top_k]]

labels = load_labels("person.txt")

interpreter = Interpreter("model.tflite")
interpreter.allocate_tensors()
_, height, width, _ = interpreter.get_input_details()[0]['shape']

image = cv2.imread("3people.jpg")
up_points = (height, width)
image = cv2.resize(image, up_points, interpolation= cv2.INTER_LINEAR)

results = classify_image(interpreter, image)
label_id, prob = results[0]

print ( label_id, prob )

Hi,

Provide the .tflite model and the test image from the first post to give it a try.

1 Like

Model, image and Label Map files:
Files

Please, use this code:

# python 2.5.3
# tensorflow 2.3.0

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import time

import numpy as np
from PIL import Image
import tensorflow as tf


def load_labels(filename):
  with open(filename, 'r') as f:
    return [line.strip() for line in f.readlines()]
	
def get_output_tensor(interpreter, index):
  """Returns the output tensor at the given index."""
  output_details = interpreter.get_output_details()[index]
  tensor = np.squeeze(interpreter.get_tensor(output_details['index']))
  return tensor
    
def detect_objects(interpreter, image, threshold):
  """Returns a list of detection results, each a dictionary of object info."""
  set_input_tensor(interpreter, image)
  interpreter.invoke()

  # Get all output details
  boxes = get_output_tensor(interpreter, 0)
  classes = get_output_tensor(interpreter, 1)
  scores = get_output_tensor(interpreter, 2)
  count = int(get_output_tensor(interpreter, 3))

  results = []
  for i in range(count):
    if scores[i] >= threshold:
      result = {
          'bounding_box': boxes[i],
          'class_id': classes[i],
          'score': scores[i]
      }
      results.append(result)
  return results


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '-i',
      '--image',
      default='3persons.jpg',
      help='image to be classified')
  parser.add_argument(
      '-m',
      '--model_file',
      default='model.tflite',
      help='.tflite model to be executed')
  parser.add_argument(
      '-l',
      '--label_file',
      #default='labelmap.txt',
      default='person.txt',
      help='name of file containing labels')
  parser.add_argument(
      '--input_mean',
      default=127.5, type=float,
      help='input_mean')
  parser.add_argument(
      '--input_std',
      default=127.5, type=float,
      help='input standard deviation')
  parser.add_argument(
      '--num_threads', default=None, type=int, help='number of threads')
  args = parser.parse_args()

  interpreter = tf.lite.Interpreter(
      model_path=args.model_file, num_threads=args.num_threads)
  interpreter.allocate_tensors()

  input_details = interpreter.get_input_details()
  output_details = interpreter.get_output_details()

  # check the type of the input tensor
  floating_model = input_details[0]['dtype'] == np.float32

  # NxHxWxC, H:1, W:2
  height = input_details[0]['shape'][1]
  width = input_details[0]['shape'][2]
  img = Image.open(args.image).resize((width, height))

  # add N dim
  input_data = np.expand_dims(img, axis=0)

  if floating_model:
    input_data = (np.float32(input_data) - args.input_mean) / args.input_std

  interpreter.set_tensor(input_details[0]['index'], input_data)
  start_time = time.time()
  interpreter.invoke()
  stop_time = time.time()
  output_data = interpreter.get_tensor(output_details[0]['index'])
  results = np.squeeze(output_data)
  
  top_k = results.argsort()[-5:][::-1]
  labels = load_labels(args.label_file)
  for i in top_k:
    print ( "i =", i )
    if floating_model:
      print('{:08.6f}: {}'.format(float(results[i]), labels[i]))
    else:  
      print('{:08.6f}: {}'.format(float(results[i] / 255.0), labels[i]))
      if labels[i]=='person' and float(results[i] / 255.0)>0.6:
        print ( "** person **" )

  print('time: {:.3f}ms'.format((stop_time - star

hello sir am getting this output after i run
output_data = interpreter.get_tensor(output_details[0][‘index’])
print(output_data)
[[[ 3.7113414 9.556558 18.571346 58.765747 ]
[ 22.771912 7.041176 41.029602 33.697575 ]
[ 40.08071 6.538019 36.90751 30.639551 ]

[341.04388 392.1772 223.59795 422.85257 ]
[375.16748 391.07074 245.52028 415.15314 ]
[403.16388 391.70615 195.44778 417.29202 ]]]