tensorflow tf.image.decode_jpeg -内容必须是标量,已获取形状[1]

ybzsozfc  于 2022-12-23  发布在  其他
关注(0)|答案(2)|浏览(148)

我已经建立了一个服务器/客户端演示图像分类的张流服务,以下教程https://github.com/tmlabonte/tendies/blob/master/minimum_working_example/tendies-basic-tutorial.ipynb

客户

它接受图像作为输入,将其转换为Base64,然后使用JSON将其传递到服务器

input_image = open(image, "rb").read()
print("Raw bitstring: " + str(input_image[:10]) + " ... " + str(input_image[-10:]))

# Encode image in b64
encoded_input_string = base64.b64encode(input_image)
input_string = encoded_input_string.decode("utf-8")
print("Base64 encoded string: " + input_string[:10] + " ... " + input_string[-10:])

# Wrap bitstring in JSON
instance = [{"images": input_string}]
data = json.dumps({"instances": instance})
print(data[:30] + " ... " + data[-10:])

r = requests.post('http://localhost:9000/v1/models/cnn:predict', data=data)
  #json.loads(r.content)
print(r.text)

服务器

一旦将模型加载为.h5,服务器必须保存为SavedModel。图像必须以Base64编码字符串的形式从客户端传递到服务器。

model=tf.keras.models.load_model('./model.h5')
  input_bytes = tf.placeholder(tf.string, shape=[], name="input_bytes")
#  input_bytes = tf.reshape(input_bytes, [])
    # Transform bitstring to uint8 tensor
  input_tensor = tf.image.decode_jpeg(input_bytes, channels=3)

    # Convert to float32 tensor
  input_tensor = tf.image.convert_image_dtype(input_tensor, dtype=tf.float32)
  input_tensor = input_tensor / 127.5 - 1.0

    # Ensure tensor has correct shape
  input_tensor = tf.reshape(input_tensor, [64, 64, 3])

    # CycleGAN's inference function accepts a batch of images
    # So expand the single tensor into a batch of 1
  input_tensor = tf.expand_dims(input_tensor, 0)

#  x = model.input
  y = model(input_tensor)

则input_bytes将成为SavedModel中predition_signature的输入

tensor_info_x = tf.saved_model.utils.build_tensor_info(input_bytes)

最后,服务器结果如下所示:

§ saved_model_cli show --dir ./ --all

signature_def['predict']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['images'] tensor_info:
        dtype: DT_STRING
        shape: ()
        name: input_bytes:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['scores'] tensor_info:
        dtype: DT_FLOAT
        shape: (1, 4)
        name: sequential_1/dense_2/Softmax:0
  Method name is: tensorflow/serving/predict

正在发送图像

当我发送图像base64时,我从服务器收到一个运行时错误,该错误涉及到输入的形状似乎不是标量:

Using TensorFlow backend.
Raw bitstring: b'\xff\xd8\xff\xe0\x00\x10JFIF' ... b'0;s\xcfJ(\xa0h\xff\xd9'
Base64 encoded string: /9j/4AAQSk ... 9KKKBo/9k=
{"instances": [{"images": "/9j ... Bo/9k="}]}
{ "error": "contents must be scalar, got shape [1]\n\t [[{{node DecodeJpeg}} = DecodeJpeg[_output_shapes=[[?,?,3]], acceptable_fraction=1, channels=3, dct_method=\"\", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"](_arg_input_bytes_0_0)]]" }

正如你从服务器上看到的input_bytes是标量的shape=[],我也试图重塑它与tf.reshape(input_bytes, []),但没有办法,我总是得到同样的错误。我没有找到任何解决方案,在互联网上和这里的Stackoverflow关于这个错误。你能建议如何修复它吗?谢谢!

2w2cym1i

2w2cym1i1#

我解决了这个问题,我想评论如何让你可以受益的解决方案!
当你发送这样的json时:

{"instances": [{"images": "/9j ... Bo/9k="}]}

实际上,当你输入[]时,你发送的是一个大小为1的数组,如果你想发送2个图像,你应该这样写

{"instances": [{"images": "/9j ... Bo/9k="}, {"images": "/9j ... Bo/9k="}]}

此处大小为2(形状= [2])
因此解决方案是在占位符中声明接受shape=[None]的任何类型的尺寸

input_bytes = tf.placeholder(tf.string, shape=[None], name="input_bytes")

那么,如果您仅发送1个图像,则矢量1可通过以下方式转换为标量:

input_scalar = tf.reshape(input_bytes, [])

我的代码中还有另一个错误,我没有考虑到在tensorflow/serving中有一个通过在json中显式声明“b64”来解码base64的功能,请参考RESTful API Encoding binary values,所以如果您发送

{"instances": [{"images": {"b64": "/9j ... Bo/9k="}}]}

服务器将自动解码base64输入并且正确的比特流将到达tf.image.decode_jpeg

gwbalxhn

gwbalxhn2#

input_bytes = tf.placeholder(tf.string, shape=[], name="input_bytes")
input_tensor = tf.image.decode_jpeg(input_bytes, channels=3)

tf.image.decode_jpeg”只能采用标量

相关问题