图像被 tf.keras.preprocessing.image.save_img 损坏

时间:2021-05-10 16:09:20

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

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

1 个答案:

答案 0 :(得分: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.]