python - 将图像转换为 one-hot 数组并返回黑色图像

标签 python numpy tensorflow one-hot-encoding

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

相关文章:

python - 在二维 numpy 数组上广播函数

Python 尝试更新 2D numpy 数组中的值,但值未更新

python - Tensorflow:在 tf.data.Dataset 中分割字符串的奇怪行为

python - 如何循环张量对象直到满足条件

python - 从剖切面提取数据

python - 给定另一个要从中切片的 id 列表来切片列表的优雅方法

python - 如何使用 NumPy+MKL 避免这种四行内存泄漏?

python - 与 Tensorflow 中的常规 LSTMCell 相比,使用 CudnnLSTM 训练时的不同结果

python - 在循环中迭代数据帧行

python - 任意两台发电机的速度差(内置函数)