为什么使用 tf.image.resize 时图像会失真?

Why is that image distorted when using tf.image.resize?

我正在使用 Tensorflow 2.4.0 并具有以下代码:

import tensorflow as tf
import numpy as np

import PIL
image=PIL.Image.open('apple.jpeg')
uiu=tf.image.resize(np.array(image), (224,224))
    
PIL.Image.fromarray(uiu.numpy(),"RGB").save("apple1.jpeg")

按理说,apple1.jpeg应该和apple.jpeg是一样的,但它们的区别如下:

apple.jpeg:

apple1.jpeg:

为什么使用 tf.image.resize 时图像会失真?

来自 tf.image.resize 的文档:return 值的类型为 float32,除非 methodResizeMethod.NEAREST_NEIGHBOR,然后return dtype 是 images.

的 dtype

因此,uiu.numpy() 的结果是一些 dtype np.float32 的 NumPy 数组,但仍然具有 0 ... 255 范围内的值,Pillow 无法将其正确保存为有意义的形象。因此,在保存图像时只需强制执行 dtype np.uint8,即而不是

PIL.Image.fromarray(uiu.numpy(),"RGB").save("apple1.jpeg")

使用这样的东西:

PIL.Image.fromarray(uiu.numpy().astype(np.uint8),"RGB").save("apple1.jpeg")

总的来说:为什么不首先使用 PIL.Image.resize

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
NumPy:         1.20.1
Pillow:        8.1.0
TensorFlow:    2.4.1
----------------------------------------