为什么 fill() 不改变数组中的所有元素?

Why doesn't fill() change all the elements in the array?

我想我可以使用 fill() 来改变数组中的所有元素,然后得到一个纯色的图像。相反,我得到了色带。

代码如下:

import numpy as np
from PIL import Image

arr3D = np.arange(500*500*3).reshape(500, 500, 3) 
print('arr3D shape = ' + str(arr3D.shape))                 
print('arr3D type = ' + str(type(arr3D)))
arr3D.fill(255)

Image.fromarray(arr3D, 'RGB').show()

这是结果:

这是您绘制图像的方式的问题,而不是 numpy 的问题。

在将数组传递给 PIL 之前,您必须将数组转换为 uint8:

import numpy as np
from PIL import Image

arr3D = np.arange(500*500*3).reshape(500, 500, 3) 
print('arr3D shape = ' + str(arr3D.shape))                 
print('arr3D type = ' + str(type(arr3D)))
arr3D.fill(255)
Image.fromarray(arr3D.astype("uint8"), 'RGB')