Skip to main content
 首页 » 编程设计

python之Inception v3 使用 base64 图像在 google ml 引擎上进行预测

2025年05月04日9Renyi-Fan

我正在尝试改变我的初始网络(在 keras 中编码)以将 base64 图像字符串作为预测的输入。之后我想将它保存为 tensorflow (.pb - 文件)网络,因为这是 Google ml 引擎所需要的。

正常的预测方式是这样的:

img = "image.jpg" 
image = image.load_img(img) 
 
 
x = image.img_to_array(image) 
x = np.expand_dims(x, axis=0) 
x = preprocess_input(x) 
score = model.predict(x) 

所以我正在尝试实现它然后像这样保存它:

input_images = tf.placeholder(dtype=tf.string, shape=[]) 
decoded = tf.image.decode_image(input_images, channels=3) 
image = tf.cast(decoded, dtype=tf.uint8) 
afbeelding = Image.open(io.BytesIO(image)) 
 
x = image.img_to_array(afbeelding) 
x = np.expand_dims(x, axis=0) 
x = preprocess_input(x) 
scores = model.predict(decoded) 
 
 
signature = predict_signature_def(inputs={'image_bytes': input_images}, 
                              outputs={'predictions': scores}) 
 
with K.get_session() as sess: 
    builder.add_meta_graph_and_variables(sess=sess, 
                                     tags=[tag_constants.SERVING], 
                                     signature_def_map={ 
                                     signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature}) 
builder.save() 

但是图像作为张量,而不是实际图像。 老实说,我不知道如何完全实现它。没有办法正确获取张量的实际值吗?真的希望有人能帮我解决这个问题。

请您参考如下方法:

您应该能够使用 tensorflow.keras.estimator.model_to_estimator() 函数将您的 Keras 模型转换为 TensorFlow 估算器。然后您可以构建和导出图表以生成预测。代码应如下所示:

from tensorflow import keras 
h5_model_path = os.path.join('path_to_model.h5') 
estimator = keras.estimator.model_to_estimator(keras_model_path=h5_model_path) 

我只对使用 tf.keras 构建的模型进行了测试,但它应该与原生 Keras 模型一起使用。

然后,为了使用处理 base64 输入的组件构建图形,您可以执行如下操作:

import tensorflow as tf 
HEIGHT = 128 
WIDTH = 128 
CHANNELS = 3 
def serving_input_receiver_fn(): 
    def prepare_image(image_str_tensor): 
        image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS) 
        image = tf.expand_dims(image, 0) 
        image = tf.image.resize_bilinear(image, [HEIGHT, WIDTH], align_corners=False) 
        image = tf.squeeze(image, axis=[0]) 
        image = tf.cast(image, dtype=tf.uint8) 
        return image 
 
    input_ph = tf.placeholder(tf.string, shape=[None]) 
    images_tensor = tf.map_fn( 
        prepare_image, input_ph, back_prop=False, dtype=tf.uint8) 
    images_tensor = tf.image.convert_image_dtype(images_tensor, dtype=tf.float32) 
 
    return tf.estimator.export.ServingInputReceiver( 
        {'input': images_tensor}, 
        {'image_bytes': input_ph}) 
 
export_path = 'exported_model_directory' 
estimator.export_savedmodel( 
    export_path, 
    serving_input_receiver_fn=serving_input_receiver_fn) 

然后可以将导出的模型上传到 Google Cloud ML 并用于提供预测服务。我花了一段时间努力让所有这些东西正常工作,并整理了一个功能齐全的代码示例,可能会有额外的用途。它在这里:https://github.com/mhwilder/tf-keras-gcloud-deployment .