Save tensors as images in TensorFlow

7.2k views Asked by At

This might be a simple question. I am just trying to do radon transform of an image and save it using functions in TensorFlow. But the result is not right. I know I can use plt.imsave() to save the image correctly, but I want to know how to do it in TensorFlow.

I am new to TensorFlow and thank you for your help.

This is the shepp-logan.jpg image I use. It is a grayscale image with size 64*64

This is the saved image

Here is my code.

from skimage.transform import radon,iradon
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

sess = tf.Session()
img = plt.imread('shepp-logan.jpg')
theta = np.linspace(0., 180., max(img.shape), endpoint=False)
sinogram = radon(img, theta=theta, circle=True)
sinogram = tf.cast(sinogram, tf.uint8)
sinogram = tf.expand_dims(sinogram, -1)
sinogram = tf.image.encode_jpeg(sinogram, quality=100, format='grayscale')
writer = tf.write_file('test_sinogram.jpg', sinogram)
sess.run(writer)
1

There are 1 answers

0
f4. On BEST ANSWER

The problem is that the function radon returns values way too high for tensorflow. Tensorflow wants values between 0 and 255 (uint8) per channel.

I didn't look why that is, but I did a quick test after looking at the values in sinogram and decided to divide by np.max(sinogram) and the result looks much closer to what you expect I believe :)

from skimage.transform import radon,iradon
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

sess = tf.Session()
img = plt.imread('shepp-logan.jpg')
theta = np.linspace(0., 180., max(img.shape), endpoint=False)
sinogram = radon(img, theta=theta, circle=True)

# scaling the values here
sinogram = 255*sinogram/np.max(sinogram)

sinogram = tf.cast(sinogram, tf.uint8)
sinogram = tf.expand_dims(sinogram, -1)
sinogram = tf.image.encode_jpeg(sinogram, quality=100, format='grayscale')
writer = tf.write_file('test_sinogram.jpg', sinogram)
sess.run(writer)

As for tensorboard, which I recommend you use, you have to use tf.summary.image: https://www.tensorflow.org/api_docs/python/tf/summary/image

And here is a guide for tensorboard: https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard