Tensorflow无法正确解码图像

时间:2017-04-13 18:51:10

标签: python image-processing matplotlib tensorflow

我是tensorflow的新手。我正在从文件中读取图像并使用tf.image.decode_jpeg解码它们,然后我用matplotlib绘制解码图像。但不知何故原始和解码的图像是不同的。

This is original Image

This is decoded image plotted with matplotlib

filenames = ['/Users/darshak/TensorFlow/100.jpg', '/Users/darshak/TensorFlow/10.jpg']
filename_queue = tf.train.string_input_producer(filenames)

reader = tf.WholeFileReader()
filename, content = reader.read(filename_queue)

image = tf.image.decode_jpeg(content, channels=3)

image = tf.cast(image, tf.float32)

resized_image = tf.image.resize_images(image, [256, 256])

image_batch = tf.train.batch([resized_image], batch_size=9)

sess = tf.InteractiveSession()

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

plt.imshow(image.eval())
plt.show()
sess.close()

1 个答案:

答案 0 :(得分:3)

问题出现是因为plt.imshow(image.eval())根据image的元素类型解释不同的图像数据。

  • 如果imagetf.uint8张量(即由tf.image.decode_jpeg()生成),它将包含从0255的值R,G和B频道,plt.imshow()(0, 0, 0)解释为黑色,将(255, 255, 255)解释为白色。

  • 当您将image转换为tf.float32张量时,它将包含来自0.0255.0的R,G和B频道的值,并且plt.imshow()(0.0, 0.0, 0.0)解释为黑色,但它将 (1.0, 1.0, 1.0) 解释为白色。所有大于1.0的值都被视为与1.0相同,因此图像显得褪色。

如果您打算将图像表示为tf.float32张量并将其可视化,则应将图像值除以255.0

image = tf.image.decode_jpeg(content, channels=3)
image = tf.cast(image, tf.float32) / 255.0
相关问题