【问题标题】:Image getting corrupted with tf.keras.preprocessing.image.save_img图像被 tf.keras.preprocessing.image.save_img 损坏
【发布时间】:2021-08-01 01:32:38
【问题描述】:

我有一个 np 数组(模型预测的分割掩码)。 我必须将此遮罩(数组)保存为图像以可视化结果。

我可以使用tf.keras.preprocessing.image.save_img 将数组保存为图像。 但是当我检查保存的图像时,发现图像有很多损坏的值。

示例代码

import numpy as np
import tensorflow as tf

# mask is prediction output from a model, of shape HxWx1, pixels can take integer values between 0 and 10.

mask = np.array([
    [[0], [0], [0], [0]],
    [[4], [4], [4], [4]],
    [[5], [5], [5], [5]],
    [[6], [6], [6], [6]]
])
print(np.unique(mask))  # unique values present are 0,4,5,6

# Save the predicted mask array as an image
tf.keras.preprocessing.image.save_img('mask.jpg', mask,  scale=False)

# Load the saved image into an array and verify values again
mask_img = tf.keras.preprocessing.image.load_img('mask.jpg', color_mode='grayscale')
loaded_mask = tf.keras.preprocessing.image.img_to_array(mask_img)

print(loaded_mask)
    # [[[1.], [1.], [1.], [1.]],
    #  [[3.], [3.], [3.], [3.]],
    #  [[6.], [6.], [6.], [6.]],
    #  [[6.], [6.], [6.], [6.]]]
print(np.unique(loaded_mask)) # unique values are 1., 3., 6.

检索到的数组与我预期的原始数组不完全相同。 在我的例子中,0 和 10 之外的值是没有意义的(值对应于一个类),我观察到像 11,12 这样的值,在某些预测中高达 13。

【问题讨论】:

    标签: python tensorflow image-processing keras python-imaging-library


    【解决方案1】:

    .png 格式保存图片。在上述示例中导致的问题来自 .jpg 格式,它使用 有损压缩算法,因此图像可能会丢失一些数据,但在 .png 中,它使用 无损压缩算法

    mask = np.array([
        [[0], [0], [0], [0]],
        [[4], [4], [4], [4]],
        [[5], [5], [5], [5]],
        [[6], [6], [6], [6]]
    ])
    print(np.unique(mask))  # unique values present are 0,4,5,6
    
    # Save the predicted mask array as an image
    tf.keras.preprocessing.image.save_img('mask.png', mask,  scale=False)
    
    # Load the saved image into an array and verify values again
    mask_img = tf.keras.preprocessing.image.load_img('mask.png', color_mode='grayscale')
    loaded_mask = tf.keras.preprocessing.image.img_to_array(mask_img)
    
    print(loaded_mask)
        # [[[1.], [1.], [1.], [1.]],
        #  [[3.], [3.], [3.], [3.]],
        #  [[6.], [6.], [6.], [6.]],
        #  [[6.], [6.], [6.], [6.]]]
    print(np.unique(loaded_mask)) # unique values are 1., 3., 6.
    
    [0 4 5 6]
    [[[0.]
      [0.]
      [0.]
      [0.]]
    
     [[4.]
      [4.]
      [4.]
      [4.]]
    
     [[5.]
      [5.]
      [5.]
      [5.]]
    
     [[6.]
      [6.]
      [6.]
      [6.]]]
    [0. 4. 5. 6.]
    

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 2017-07-08
      • 1970-01-01
      • 2017-01-09
      • 2012-11-18
      相关资源
      最近更新 更多