Reputation: 4052
I am converting some Image transformation code to use tensorflow.
My image is passed in as a base64 string. Using the following function the base64 string can be decoded and opened as a np.array:
def load_color_image_base64(image_base64):
img_pil = Image.open(BytesIO(base64.b64decode(image_base64))).convert("RGB")
return np.array(img_pil)
However, when I pass the same string to the following tensorflow code I get an error:
self._image = tf.image.decode_jpeg(tf.decode_base64(self._image_b64), channels=3)
The error I get is:
tf.decode_base64(self._image_b64), channels=3) File "/Users/jameskelly/anaconda/envs/im2volume/lib/python2.7/site-packages/tensorflow/python/ops/gen_string_ops.py", line 106, in decode_base64 "DecodeBase64", input=input, name=name) File "/Users/jameskelly/anaconda/envs/im2volume/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper op_def=op_def) File "/Users/jameskelly/anaconda/envs/im2volume/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2956, in create_op op_def=op_def) File "/Users/jameskelly/anaconda/envs/im2volume/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1470, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): Invalid character found in base64. [[Node: DecodeBase64 = DecodeBase64[_device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_Placeholder_2_0_2)]]
It should be noted that this code is behind a flask api. When I run the class directly, loading the image from disk and converting it directly to base64, both cases work.
I have also converted the base64 string to a python str
type, as it was being passed in as unicode
, the error message did not change.
Upvotes: 2
Views: 1667
Reputation: 199
You must use base64.urlsafe_b64encode
which, as Debangshu Paul mentions, uses '-' instead of '+' and '_' instead of '/'.
See https://docs.python.org/3/library/base64.html#base64.urlsafe_b64encode for more info.
Upvotes: 2
Reputation: 344
Replace "/" with "_" and "+" with "-" in the base64 string. Worked for me. For more info refer this: https://www.tensorflow.org/versions/r1.14/api_docs/python/tf/io/decode_base64
Upvotes: 0