How do I convert from a tensorflow tensor to an image without using numpy?

Viewed 652

I was trying to use numpy.asarray(tensor) to convert a tensor into an ndarray. Then, I was planning to use PIL to convert that ndarray into a downloadable image. However, since I was running this code on a TPU, it got held up the numpy conversion and could not proceed to the PIL step. Is there any way to convert from a tensor to an image directly, without converting to an ndarray?

1 Answers

Maybe try using tf.keras.preprocessing.image.array_to_img to convert a tensor to a PIL image:

import tensorflow as tf
import matplotlib.pyplot as plt

img = tf.random.normal((100, 100, 3))
pil_img = tf.keras.preprocessing.image.array_to_img(img)
plt.imshow(pil_img)
<matplotlib.image.AxesImage at 0x7f3483d71310>

enter image description here

Related