首页 > 解决方案 > 图像被 tf.keras.preprocessing.image.save_img 损坏

问题描述

我有一个 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。

标签: pythontensorflowimage-processingkeraspython-imaging-library

解决方案


.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.]

推荐阅读