Tensorflow 无法正确解码图像

BeP*_*ant 0 python image-processing matplotlib tensorflow

我是张量流新手。我正在从文件中读取图像并使用 tf.image.decode_jpeg 对其进行解码,然后使用 matplotlib 绘制解码图像。但不知怎的,原始图像和解码图像是不同的。

这是原始图片

这是用 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()
Run Code Online (Sandbox Code Playgroud)

mrr*_*rry 5

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

  • 如果image是一个tf.uint8张量(即,由 产生tf.image.decode_jpeg()),它将包含R、G 和 B 通道的从0到 的值,并解释为黑色和白色。255plt.imshow()(0, 0, 0)(255, 255, 255)

  • 当您转换imagetf.float32张量时,它将包含R、G 和 B 通道的从0.0到 的值,并解释为黑色,但它解释为白色。所有大于 的值都将被视为与 相同,因此图像会出现变色。255.0plt.imshow()(0.0, 0.0, 0.0)(1.0, 1.0, 1.0)1.01.0

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

image = tf.image.decode_jpeg(content, channels=3)
image = tf.cast(image, tf.float32) / 255.0
Run Code Online (Sandbox Code Playgroud)