我有一个由 3 个灰度图像组成的 numpy 数组,其中只有 0 和 255 个值(shape: (3, 512, 512)
)。我使用 tf.one_hot
(shape: (3, 512, 512, 2)
)将它们转换为 2 个类。现在,我试图通过 np.argmax 将它们恢复到原始形式。但当我阅读图像时,它们都是黑色的。
labels = []
labels.append(label_1)
labels.append(label_2)
labels.append(label_3)
labels = np.asarray(labels)
print(labels.shape) # (3, 512, 512)
sess = tf.InteractiveSession()
labels = tf.one_hot(labels, 2) # (3, 512, 52, 2)
print(labels.shape)
#print(labels)
labels = labels.eval() # to convert to numpy array from tensor
imgs = np.argmax(labels, axis=3) # also tried tf.argmax
print(imgs.shape) # (3, 512, 512)
for i in range(imgs.shape[0]):
image = imgs[i]
print(img.shape) # (512, 512)
indices = np.where(image > 0)
print(indices) # array([], dtype=int64), array([], dtype=int64)
print(indices)
image = Image.fromarray(image, 'L')
image.show() # black images, values all zero
我确信我错过了一些非常简单的东西,但无法弄清楚。任何帮助将不胜感激。谢谢。
编辑:
我检查了数组中具有非零值的索引。但所有的值似乎都是零。所以,不是显示图像的问题。我认为问题出在 argmax
但我不知道是什么。
最佳答案
Argmax 返回某个维度上出现最大值的索引。在您的情况下,您在长度为 2 的维度上获取 argmax,因此它为 (3, 512, 512) 数组中的每个位置返回 0 或 1。这两个选项在 8 位尺度上都很暗,并且会显示为黑色!您必须确保将二进制图像显示为二进制。
我以前没有使用过这个库,但也许可以尝试mode='I'
?或这里的一些其他模式 https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes 。 argmax 的返回类型很重要。
关于python - 将图像转换为 one-hot 数组并返回黑色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49385159/