如何通过将base64图像传递给重新训练的初始模型来获得gcloud预测?

2024-05-18 14:31:13 发布

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

我试图用gcloud获得一个预测,方法是将base64编码的图像传递给重新训练的初始模型,方法与Davide Biraghithispost中采用的方法类似。 当使用'DecodeJpeg/contents:0'作为输入时,我在尝试获得预测时也会遇到相同的错误,因此我采用了稍微不同的方法。在

按照rhaertel80在他对这个post的回答中的建议,我创建了一个图形,它将jpeg图像作为'B64Connector/input'中的输入,对其进行预处理并将其馈送给'ResizeBilinear:0'中的初始模型。在

预测返回值,虽然是错误的(我正在另一篇文章中寻找解决方案),但至少不会失败。我用作输入的占位符是

images_placeholder = tf.placeholder(dtype=tf.string, shape=(None,), name='B64Connector/input')

我把它添加到模型输入中

^{pr2}$

作为Davide,我遵循这些帖子中的建议:herehere和{a7},我正在尝试用

    gcloud beta ml predict --json-instances=request.json --model=MODEL

其中文件request.json已使用此代码获得

jpgtxt = base64.b64encode(open(imagefile ,"rb").read())

with open( outputfile, 'w' ) as f :
  f.write( json.dumps( {"b64_bytes": {"b64": jpgtxt}} ) )

我想知道为什么当我使用'DecodeJpeg/contents:0'作为输入时预测会失败,而当我使用这种不同的方法时却不会失败,因为它们看起来和我几乎一样:我使用相同的脚本来生成实例(更改input_key),使用相同的命令行来请求预测

有没有一种方法可以将fed to 'B64Connector/input:0'传递给'DecodeJpeg/contents:0'以获得正确的预测?在


Tags: 方法图像jsoninputtf错误contents建议
1条回答
网友
1楼 · 发布于 2024-05-18 14:31:13

这里我将更详细地描述我的方法以及如何使用images_占位符。在

我定义了一个调整图像大小的函数:

  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=MODEL_INPUT_DEPTH)

    # 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, [MODEL_INPUT_HEIGHT, MODEL_INPUT_WIDTH], align_corners=False)
    image = tf.squeeze(image, squeeze_dims=[0])
    image = tf.cast(image, dtype=tf.uint8)
    return image

以及一个生成图的定义的函数,在该图中进行大小调整,并在其中定义和使用images_placeholder

^{pr2}$

此外,我使用以下代码将调整大小的图形与初始图形合并。我是否可以使用类似的方法将images_placeholder直接链接到'DecodeJpeg/contents:0'?在

def concatenate_to_inception_graph( b64_graph_def ):

  model_dir = INPUT_MODEL_PATH
  model_filename = os.path.join(
       model_dir, 'classify_image_graph_def.pb')

  with tf.Session() as sess:

    # Import the b64_graph and get its output tensor
    resized_b64_tensor, = (tf.import_graph_def(b64_graph_def, name='',
                             return_elements=['B64Connector/output:0']))

    with gfile.FastGFile(model_filename, 'rb') as f:
      inception_graph_def = tf.GraphDef()
      inception_graph_def.ParseFromString(f.read())

      # Concatenate b64_graph and inception_graph
      g_1 = tf.import_graph_def(inception_graph_def, name='inception',
               input_map={'ResizeBilinear:0' : resized_b64_tensor} )

    return sess.graph

相关问题 更多 >

    热门问题