PIL.Image.open和tf.image.decode_jpeg的返回值之间的差异

时间:2017-06-13 07:25:28

标签: python image tensorflow python-imaging-library

我使用PIL.Image.open和tf.image.decode_jpeg将图像文件解析为数组。 但发现PIL.Image.open()中的像素值与tf.image.decode_jpeg不同。 为什么会这样?

谢谢!

CodeOutput:

tf 100 100 [132 145 161]
pil 100 100 [134 147 164]

mycode的:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from datetime import datetime
import math
import time

import numpy as np
import tensorflow as tf

def decode_jpeg(image_file):
  from PIL import Image
  im = Image.open(image_file)
  data = np.array(im)
  return data

def tfimageread(filenames):
  filename_queue = tf.train.string_input_producer(filenames)
  reader = tf.WholeFileReader(name='image_reader')
  key, value = reader.read(filename_queue)
  uint8image = tf.image.decode_jpeg(value, channels=3)

  with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = []
    for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
      threads.extend(qr.create_threads(sess, coord=coord, daemon=True, start=True))
    image = sess.run(uint8image)
    coord.request_stop()
    coord.join(threads, stop_grace_period_secs=10)
    return image

if __name__ == '__main__':
  image_file = '。/o_1bchv9keu625336862107241874241888.jpg'
  image_tf = tfimageread([image_file])
  image_pil = decode_jpeg(image_file)
  i, j = 100, 100
  print ("tf %d %d %s" % (i,j,image_tf[i][j]))
  print ("pil %d %d %s" % (i,j,image_pil[i][j]))

1 个答案:

答案 0 :(得分:2)

此问题的常见原因是tensorflow在解压缩jpeg时尝试采用快捷方式。这为图像读取提供了pretty large speedup,这可能是训练某些CNN的瓶颈,但确实会使像素值有些抖动。

幸运的是,开发人员已经公开了关闭其中一些效率的选项。特别要检查argument dct_method

尝试将对tf.image.decode_jpeg的呼叫更改为:

tf.image.decode_jpeg(value, channels=3, dct_method='INTEGER_ACCURATE')

您可能还需要弄混fancy_upscaling,这取决于您正在读取的图像种类以及您的软件正在使用的libjpeg底层版本中发生的其他情况。