【问题标题】:Why is that image distorted when using tf.image.resize?为什么使用 tf.image.resize 时该图像失真?
【发布时间】:2021-02-21 07:27:44
【问题描述】:

我使用的是 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时图片会变形?

【问题讨论】:

    标签: python-3.x python-imaging-library tensorflow2.0 image-resizing


    【解决方案1】:

    来自tf.image.resize 的文档:返回值的类型为float32,除非methodResizeMethod.NEAREST_NEIGHBOR,那么返回的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
    ----------------------------------------
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2022-11-11
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      相关资源
      最近更新 更多