如何将解释器输出数组转换回 base64 图像?

How to convert interpreter output array back to base64 image?

我正在加载图像并使用我训练的 tflite 对其进行处理,我想从输出中提取 base64。我该怎么做?

在将模型转换为 tflite 之前,base64 结果只是输出字典中的一个值。现在输出不一样了,不知道怎么找

这里是我的拦截器的输入输出细节,供参考

[{'name': 'TFLiteInput', 'dtype': <class 'numpy.float32'>, 'shape': array([  1, 256, 256,   3]), 'index': 1, 'quantization': (0.0, 0)}]

[{'name': 'TFLiteOutput', 'dtype': <class 'numpy.float32'>, 'shape': array([  1, 256, 256,   3]), 'index': 2, 'quantization': (0.0, 0)}]

控制台输出:

[[[[1. 1. 0.]
   [1. 1. 1.]
   [1. 1. 1.]
   ...
   [1. 1. 1.]
   [1. 1. 0.]
   [1. 1. 1.]]

  [[1. 1. 0.]
   [1. 1. 1.]
   [1. 1. 1.]
   ...

<class 'numpy.ndarray'>

我的代码:

import numpy as np
import tensorflow as tf
import base64, json, cv2

interpreter = tf.contrib.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

input_file = "309.png"
im = cv2.imread(input_file)
im = im.astype(np.float32, copy=False)
input_image = im
input_image = np.array(input_image, dtype=np.uint8)
input_image = np.expand_dims(input_image, axis=0)

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

input_data = np.array(input_image, dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

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

print(output_data)
print(type(output_data))

问题与 TFLite 解释器无关。本质上你想要序列化一个包含图像的 Numpy 数组。

Base64是一种编码格式,里面可以是原始数据,也可以是其他格式(如PNG、JPEG等)。例如,下面是编写 PNG 并将其编码为 Base64 的示例片段:

import numpy as np
from PIL import Image
import io
import base64

image = Image.fromarray(output_data)
with io.BytesIO() as output:
  image.save(output, format="PNG")
  base64_img = base64.b64encode(output.getvalue())

您可以轻松更改代码以使用 JPEG 或原始数据。