我成功地使用以下代码将 TF2 图像分割模型保存并部署到 AI Platform:
@tf.function(input_signature=[tf.TensorSpec(shape=(None), dtype=tf.string)])
def serving(input_image):
# Convert bytes of jpeg input to float32 tensor for model
def _input_to_feature(image_bytes):
img = tf.image.decode_jpeg(image_bytes, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32) / 255.0
img = tf.image.resize_with_pad(img, 256, 256)
return img
img = tf.map_fn(_input_to_feature, input_image, dtype=tf.float32)
# Predict
pred = model(img)
def _pred_to_image(pred):
pred = tf.cast(pred * 255, dtype=tf.uint8)
img_str = tf.image.encode_png(pred, compression=-1, name=None)
return img_str
img_str = tf.map_fn(_pred_to_image, pred, dtype=tf.string)
return img_str
tf.saved_model.save(model, export_dir=checkpoint_dir+'/saved_model', signatures=serving)
但是,在发送这样的请求时出现此错误:
img_str = base64.b64encode(open('sample_372.jpg', "rb").read()).decode()
response = service.projects().predict(name=name,body={'instances': [img_str]}).execute()
HttpError: <HttpError 400 when requesting https://ml.googleapis.com/v1/projects/nerveblox-268109/models/femoral/versions/v6:predict?alt=json returned "{ "error": "Expected image (JPEG, PNG, or GIF), got unknown format starting with \'/9j/4AAQSkZJRgAB\'\n\t [[{{node DecodeJpeg}}]]" }">
有人遇到过类似的问题吗?这似乎是一个问题tf.image.decode_jpeg
。我也尝试过tf.image.decode_image
并得到了类似的错误。我可以使用tf.image.decode_jpeg
我的本地 Base64 编码,所以这个函数应该能够工作,但不知何故它没有在服务器中接收相同的输入!