我的程序使用 python PIL class 从二维数组输出 RGBA 中的奇怪颜色。我如何解决它?

My program is outputting strange colors in RGBA from a 2D Array using the python PIL class. How do I fix it?

def arrayconv(a):
    black = [0, 0, 0, 1]   #RGBA value for black
    white = [255, 255, 255, 1]   #RGBA value for white
    red = [255, 0, 0, 1]   #RGBA value for red
    b = np.zeros(shape=(10, 10), dtype=object)   #creates an array of zeroes
    for i in range(10):
        for j in range(10):
            if a[i][j] == 0:   #Copies the values of a into b except in rgba. 
                b[i][j] = black
            if a[i][j] == 1:
                b[i][j] = white
            if a[i][j] == 2:
                b[i][j] = red
    print(b)
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().

我正在编写一个解决十乘十像素迷宫的程序。这段代码来自程序的后端,它应该将 0s、1s 和 2s 的数组转换为具有相应 rgba 值的新数组。那部分工作正常。

但是当我使用 fromarray() 打印这张图片时,它的颜色与预期的不同。图像以正确数量的颜色(三种)和正确的排列打印出来,但颜色为蓝色或绿色。同样不正确的配色方案也不会每次都打印出来。

您必须为 b 创建一个包含 dtype='uint8' 的 3 维数组。

这段代码对我有用:

def arrayconv(a):
    b = np.zeros(shape=(a.shape[0], a.shape[1], 4), dtype="uint8")   #creates an array of zeroes
    colormap = {
        0: (0, 0, 0, 1),
        1: (255, 255, 255, 1),
        2: (255, 0, 0, 1),
    }
    for index_x, row in enumerate(a):
        for index_y, pixel in enumerate(row):
                b[index_x, index_y] = colormap[pixel]
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().

#create test data
data = [random.randint(0, 2) for i in range(100 * 100)]
data = np.reshape(data, (100, 100))
img = arrayconv(data)
img.show()

如果你只改变

 b = np.zeros(shape=(10, 10), dtype=object)

 b = np.zeroes(shape=(10, 10, 4), dtype="uint8")

您的代码应该也能正常工作。