sjamil
sjamil

Reputation: 51

Accepting base64-images as input for TensorFlow model

I am trying to export my TensorFlow image-classifying model such that it accepts base64 strings as input.

I have tried to implement the solution that is provided on this question, however I am getting the following error:

"InvalidArgumentError: Shape must be rank 0 but is rank 1 for 'DecodeJpeg_1' (op: 'DecodeJpeg') with input shapes: [?]."

The error appears as a result of the code on line 4.

export_dir = '~/models/1'
builder = saved_model_builder.SavedModelBuilder(export_dir)
image = tf.placeholder(dtype=tf.string, shape=[None], name='source')
decoded = tf.image.decode_jpeg(image)
scores = build_model(decoded)
signature = predict_signature_def(inputs={'image_bytes': image},
                                 outputs={'output': scores})

with K.get_session() as sess:
    builder.add_meta_graph_and_variables(sess=sess,
                                         tags=[tag_constants.SERVING],
                                         signature_def_map={'predict': signature})
    builder.save()
sess.close()

Also,

I see that on line 5, "scores" provides the output of the model based on the build_model function. However, I can't find in the original question's answers or in the TensorFlow documentation where this function comes from.

Upvotes: 2

Views: 1368

Answers (1)

user11530462
user11530462

Reputation:

As per the Tutorials mentioned in the tf.decode_jpeg, we should use image = tf.io.read_file(path) before using image = tf.image.decode_jpeg(image).

Working code example is shown below:

import tensorflow as tf

path = '/home/mothukuru/Jupyter_Notebooks/Stack_Overflow/cat.jpeg'

z = tf.placeholder(tf.string, shape=())

image = tf.io.read_file(path)

image = tf.image.decode_jpeg(image)

with tf.Session() as sess:
   v = sess.run([image], feed_dict={z:path})
   print(v)

Output of the above code is an array as shown below:

[array([[[216, 216, 216],
        [218, 218, 218],
        [220, 220, 220],
        ...,
        [226, 228, 217],
        [221, 223, 212],
        [221, 223, 212]],

       [[216, 216, 216],
        [217, 217, 217],
        [219, 219, 219],
        ...,
        [225, 227, 216],
        [222, 224, 213],
        [222, 224, 213]],

       [[216, 216, 216],
        [216, 216, 216],
        [218, 218, 218],
        ...,
        [223, 225, 214],
        [222, 224, 213],
        [222, 224, 213]],

       ...,

       [[240,  20,  64],
        [240,  20,  64],
        [243,  23,  67],
        ...,
        [  7,   3,   0],
        [  8,   4,   1],
        [  8,   4,   1]],

       [[241,  21,  65],
        [240,  20,  64],
        [245,  25,  69],
        ...,
        [  7,   3,   0],
        [  8,   4,   1],
        [  8,   4,   1]],

       [[242,  22,  66],
        [239,  19,  63],
        [246,  26,  70],
        ...,
        [  7,   3,   0],
        [  8,   4,   1],
        [  8,   4,   1]]], dtype=uint8)]

Upvotes: 1

Related Questions