如何将文件输入tflite模型进行推理(ValueError:无法设置tensor:获取类型为FLOAT32的值,但输入170需要类型为UINT8)

2024-05-01 03:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解我应该在这里做什么。我试图对this模型进行推理。我已将图像预处理为224x224大小,并使用规范化将值缩放到[0,1]之间,如代码所示


import numpy as np
from numpy import asarray
import tensorflow as tf
import os
import sys
from PIL import Image

def process_image(image_path):
    image = Image.open(image_path)
    new_image = image.resize((224,224))
    np_image = asarray(new_image)

    min = np_image.min()
    max = np_image.max()    

    # normalize to the range 0-1
    np_image = np_image.astype('float32')
    np_image -= min
    np_image /= (max - min)

    return [np_image]

这是它的输出

[array([[[0.5411765 , 0.5372549 , 0.03529412],
        [0.24705882, 0.5372549 , 0.53333336],
        [0.03137255, 0.24705882, 0.52156866],
        ...,
        [0.24705882, 0.60784316, 0.6039216 ],
        [0.10196079, 0.24705882, 0.5686275 ],
        [0.5647059 , 0.0627451 , 0.24705882]],

然后,我尝试将这个结果放入模型中并进行推理。然而,我不断地得到这个错误

ValueError: Cannot set tensor: Got value of type FLOAT32 but expected type UINT8 for input 170, name: module/hub_input/images_uint8

你知道怎么修吗?我试图简单地将类型改回uint8,但是所有的RGB值都变为0,因为所有的值都是小于1的小数

下面是代码的其余部分

# Load interpreter
interpreter = tf.lite.Interpreter(model_path="aiy_vision_classifier_birds_V1_2.tflite")
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

print(input_details)
print(output_details)

interpreter.allocate_tensors()

# Inputting the image
image = process_image('Images/Processed/blue_Jay_processed.png') # This is the function shown above
print(image)
interpreter.set_tensor(input_details[0]['index'], image)

# run the inference
interpreter.invoke()

output_data = interpreter.get_tensor(input_details[0]['index'])

print("the output is {}".format(output_data))

此外,以下是输入和输出的详细信息:

[{'name': 'module/hub_input/images_uint8', 'index': 170, 'shape': array([ 1, 224, 224, 3], dtype=int32), 'shape_signature': array([ 1, 224, 224, 3], dtype=int32), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.0078125, 128), 'quantization_parameters': {'scales': array([0.0078125], dtype=float32), 'zero_points': array([128], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]

[{'name': 'module/prediction', 'index': 171, 'shape': array([ 1, 965], dtype=int32), 'shape_signature': array([ 1, 965], dtype=int32), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.00390625, 0), 'quantization_parameters': {'scales': array([0.00390625], dtype=float32), 'zero_points': array([0], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]


Tags: theimageimportnumpyinputoutputnpdetails