首页 > 解决方案 > 尝试使用 PIL 生成随机图片,但得到奇怪的结果

问题描述

生成的图片

我使用这段代码通过填充每个像素来生成随机图片,但是为什么我得到这个奇怪的输出(图片在上面的链接中)?图中有平行的红、绿、蓝竖线。

#<Python 3.8>
from PIL import Image
import numpy as np
data=np.random.randint(low=0,high=256,size=128*128*3)
data=data.reshape(128,128,3)
Image.fromarray(data,'RGB')

标签: pythonimagepython-imaging-library

解决方案


PIL 的 RGB 模式需要 8 位颜色通道,但您的数组很可能具有int32. 每个整数的 75% 由未使用的 0 位组成,这就是为什么 75% 的图像是黑色条纹的原因。

尝试将您的数据设置dtypeunit8当您调用时randint

from PIL import Image
import numpy as np
data=np.random.randint(low=0,high=256,size=128*128*3, dtype=np.uint8)
data=data.reshape(128,128,3)
Image.fromarray(data,'RGB').save("output.png")

结果(多种可能性中的一种):

在此处输入图像描述


推荐阅读