PIL 将两个相同的阵列显示为不同的图像

PIL shows two identical arrays as different images

我正在创建一个函数来为给定要着色的索引的矩阵“着色”。

简化示例:我有一个由 0 组成的 2x2 矩阵,我想用 1 为矩阵中的第二个和第四个元素“着色”。 输出将是:

[[0,1]
 [0,1]]

现在,这是我的代码(尝试将矩阵的所有奇数元素涂成白色):

def createMatrix(w, h, bg, value, seq):
    data = np.full((h, w, 3), bg, dtype=uint8)
    rows = (seq-1)//w
    cols = (seq-1)%w
    if rows.size and cols.size:
        data[rows,cols] = value
    return data
data = createMatrix(w=4, h=4, bg=0, value=255, seq=array([1,3,5,7,9,11,13,15]))
Image.fromarray(data, 'RGB').resize((1024, 1024), Image.BOX).show()

这段代码工作得很好,但它只允许我使用红色、绿色和蓝色的值相同的颜色。然后我试图概括这样的功能:

def createMatrix1(w, h, bg, value, seq):
    data = np.tile(bg, (h, w, 1))
    rows = (seq-1)//w
    cols = (seq-1)%w
    if rows.size and cols.size:
        data[rows,cols] = value
    return data

但出于某种原因,此代码 returns 两个截然不同的结果:

data = createMatrix(w=4, h=4, bg=0, value=255, seq=array([1,3,5,7,9,11,13,15]))
data1 = createMatrix1(w=4, h=4, bg=(0,0,0), value=(255,255,255), seq=array([1,3,5,7,9,11,13,15]))
if np.array_equal(data, data1): print('The matrices are identical')
Image.fromarray(data, 'RGB').resize((1024, 1024), Image.BOX).show()
Image.fromarray(data1, 'RGB').resize((1024, 1024), Image.BOX).show()

尽管 datadata1 相同。 怎么回事?

它们是不同的数据类型,即使它们的计算结果为真。

data.dtype
dtype('unit8')

data1.dtype
dtype('int32')

您可以转换它,图像将变成彩色图像。

data = data.astype('int32')

或修改函数使用int32