图像与Keras(PIL)和TensorFlow调整之间的矛盾?

问题描述 投票:11回答:1

我对之间的明显不一致窃听:

  1. 图像调整大小从keras.preprocessing官能团,其是围绕PIL函数的包装
  2. 在TensorFlow的tf.image图像缩放功能。

我正在训练一个深度学习模型计算机视觉任务与Keras(实际上,与tf.keras,但此处无关紧要)。然后我用发球份量TF,这就要求我将图像发送到模型中作为编码的字节串,在那里它们被使用之前tf.image.decode_png通过模型图去解码的模型。

当我调整图像时出现问题。用双线性内插(或任何其它方法)改变给出具有PIL不同的结果与用tf.image,以使得由模型的变化进行分类,这取决于函数I使用这样的程度。

下面的代码提供可再现的例子。

import numpy as np 
from PIL import Image
from keras.preprocessing.image import load_img, img_to_array
import tensorflow as tf

# Generate an 'image' with numpy, save as png
np.random.seed(42)
image = np.random.randint(0, 255, size=(256, 256, 3)).astype(np.uint8)
Image.fromarray(image).convert("RGB").save('my_image.png')

现在,让我们加载图像两种方式。首先从Keras的PIL包装,作为模型的训练过程中,随后被编码成一个二进制字符串,并用TensorFlow解码功能,如在我的模型服务器。

# Using Keras PIL wrappers
keras_image = img_to_array(load_img('./my_image.png')) 

# Using TF functionalities
with tf.Session() as sess:
    with open('./my_image.png', 'rb') as f:
        tf_image_ = tf.image.decode_png(f.read())
    tf_image = sess.run(tf_image_)

到目前为止好,因为这两个图像是完全一样的(除了D型,如Keras已经铸造到FLOAT32图像):

# Assert equality
np.array_equal(keras_image, tf_image)
> True

重复此代码然而调整给出了不同的结果:

# Using Keras PIL wrappers, with resizing
keras_image_rs = img_to_array(load_img('./my_image.png',
                             target_size=(224, 224),
                             interpolation='bilinear'))

# Using TF functionalities, with resizing
with tf.Session() as sess:
    with open('./my_image.png', 'rb') as f:
        tf_image_ = tf.image.decode_png(f.read())
        # Add and remove dimension
        # As tf.image.resize_* requires a batch dimension
        tf_image_ = tf.expand_dims(tf_image_, 0)
        tf_image_ = tf.image.resize_bilinear(tf_image_,
                                            [224, 224], 
                                             align_corners=True)
        tf_image_ = tf.squeeze(tf_image_, axis=[0])

    tf_image_rs = sess.run(tf_image_)

# Assert equality
np.array_equal(keras_image_rs, tf_image_rs)
> False

两幅图像之间的平均绝对差是不可忽视的:

np.mean(np.abs(keras_image_rs - tf_image_rs))
7.982703

我打了align_corners说法,并试图其他可用的插值方法为好。无给输出与PIL缩放图像时相同。这是很烦人的,因为它给我的培训和测试结果之间的偏差。有没有人有一个想法,是什么原因导致这种行为,或者对如何解决这个问题?

python tensorflow keras deep-learning python-imaging-library
1个回答
9
投票

完全描述的行为符合什么写这篇文章在:How Tensorflow’s tf.image.resize stole 60 days of my life

简而言之:是的,PIL / sklearn / OpenCV的和其他常见的库图像处理有正确的行为,而tf.image.resize具有不同的行为,不会为了不打破旧训练的模型来改变。

因此,你应该使用的计算图表外的同一个库总是你进行预处理图像。

链接到相关的github上线:https://github.com/tensorflow/tensorflow/issues/6720

© www.soinside.com 2019 - 2024. All rights reserved.