Google机器学习中如何将JPEG图像转换为JSON文件

4
我正在使用Google Cloud ML,希望能够对JPEG图片进行预测。为此,我想使用以下命令:
gcloud beta ml predict --instances=INSTANCES --model=MODEL [--version=VERSION]

(https://cloud.google.com/ml/reference/commandline/predict)

“Instances”是一个包含有关图像的所有信息的json文件的路径。如何从我的jpeg图像创建json文件?

非常感谢!

3个回答

7

第一步是确保您导出的图形具有可以接受JPEG数据的占位符和运算。请注意,CloudML假定您正在发送一批图像。我们必须使用tf.map_fn来解码并调整一批图像的大小。根据模型,可能需要对数据进行额外的预处理以规范化数据等。如下所示:

# Number of channels in the input image
CHANNELS = 3

# Dimensions of resized images (input to the neural net)
HEIGHT = 200
WIDTH = 200

# A placeholder for a batch of images
images_placeholder = tf.placeholder(dtype=tf.string, shape=(None,))

# The CloudML Prediction API always "feeds" the Tensorflow graph with
# dynamic batch sizes e.g. (?,).  decode_jpeg only processes scalar
# strings because it cannot guarantee a batch of images would have
# the same output size.  We use tf.map_fn to give decode_jpeg a scalar
# string from dynamic batches.
def decode_and_resize(image_str_tensor):
  """Decodes jpeg string, resizes it and returns a uint8 tensor."""

  image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS)

  # Note resize expects a batch_size, but tf_map supresses that index,
  # thus we have to expand then squeeze.  Resize returns float32 in the
  # range [0, uint8_max]
  image = tf.expand_dims(image, 0)
  image = tf.image.resize_bilinear(
      image, [HEIGHT, WIDTH], align_corners=False)
  image = tf.squeeze(image, squeeze_dims=[0])
  image = tf.cast(image, dtype=tf.uint8)
  return image

decoded_images = tf.map_fn(
    decode_and_resize, images_placeholder, back_prop=False, dtype=tf.uint8)

# convert_image_dtype, also scales [0, uint8_max] -> [0, 1).
images = tf.image.convert_image_dtype(decoded_images, dtype=tf.float32)

# Then shift images to [-1, 1) (useful for some models such as Inception)
images = tf.sub(images, 0.5)
images = tf.mul(images, 2.0)

# ...

此外,我们需要确保正确标记输入内容。在这种情况下,关键字(映射中的键)的名称必须以“_bytes”结尾。发送基于base64编码的数据时,这将告诉CloudML预测服务需要解码数据。
inputs = {"image_bytes": images_placeholder.name}
tf.add_to_collection("inputs", json.dumps(inputs))
命令期望的数据格式应该是这样的:
{"image_bytes": {"b64": "dGVzdAo="}}

(请注意,如果您的模型的唯一输入是image_bytes,则可以简化为{"b64": "dGVzdAo="}。)
例如,要从磁盘上的文件创建此内容,您可以尝试以下操作:
echo "{\"image_bytes\": {\"b64\": \"`base64 image.jpg`\"}}" > instances

然后像这样将其发送到服务端:
gcloud beta ml predict --instances=instances --model=my_model

请注意,在直接向服务发送数据时,您发送的请求正文需要包装在“instances”列表中。因此,上述gcloud命令实际上将以下内容作为HTTP请求的正文发送到服务端:
{"instances" : [{"image_bytes": {"b64": "dGVzdAo="}}]}

谢谢你的回答!也许我不太明白我需要做什么。实际上,当我发送请求时,它返回:错误:'Prediction failed: '。我在这里写下了我的问题(http://stackoverflow.com/questions/41261701/how-make-correct-predictions-of-jpeg-image-in-cloud-ml) - Davide Biraghi

2

补充之前的回答...

谷歌发布了一篇关于图像识别任务的博客文章,以及一些相关的代码,这些都直接回答了你的问题,同时也可以解决你可能遇到的其他问题。其中包括一个images_to_json.py文件,可帮助构建json请求。


0
在Python中,您可以使用以下代码创建与“gcloud ml-engine predict”配合使用的base64 JSON文件:
import json
import base64
with open('path_to_img.jpg', 'rb') as f:
    img_bytes = base64.b64encode(f.read())
json_data = {'image_bytes': {'b64': img_bytes.decode('ascii')}}
with open('path_to_json_file.json', 'w+') as f:
    json.dump(json_data, f)

我花了很长时间在TensorFlow Keras模型和Google Cloud ML上进行设置,终于使所有东西都能够正常工作。在最后一切都顺利之后,我编写了一个代码示例,希望它能够帮助那些在部署TF模型到Google Cloud ML方面遇到同样问题的人们。该示例代码可以在这里找到: https://github.com/mhwilder/tf-keras-gcloud-deployment

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接