I have a string Tensor object that I produced by calling tf.io.encode_jpeg
on an image Tensor (Documentation for encode_jpeg).
How do I convert this string Tensor into a PIL Image?
I've tried calling Image.fromarray(encoded_tensor.numpy())
, but this returns AttributeError: 'bytes' object has no attribute '__array_interface__'
.
CodePudding user response:
You appear to have an in-memory (rather than on-disk) JPEG-encoded image. You can check if that is correct by printing the start of the buffer:
print(encoded_tensor[:10])
and seeing if it starts with the JPEG magic number ff d8 ff
.
If so, you need to wrap it in a BytesIO
and open it into a PIL Image
with:
from io import BytesIO
from PIL import Image
im = Image.open(BytesIO(encoded_tensor))
CodePudding user response:
The error here is caused because you are not decoding the image. To decode the image, use tf.io.decode_jpeg
. Please find the working code below.
import tensorflow as tf
from PIL import Image
img=tf.keras.utils.load_img('/content/dog.1.jpg')
img=tf.keras.utils.img_to_array(img)
#encode_jpeg encodes a tensor of type uint8 to string
encode_img=tf.io.encode_jpeg(img,'rgb')
#decode_jpeg decodes the string tensor to a tensor of type uint8
decode_img=tf.io.decode_jpeg(encode_img)
Image.fromarray(decode_img.numpy())