python - Image.fromarray(pixels) 和 np.array(img) 是否应该保持数据不变?

标签 python numpy python-imaging-library

我尝试使用 PIL 中的 Image.fromarray() 函数生成 PNG,但没有获得预期的图像。

arr=np.random.randint(0,256,5*5)
arr.resize((5,5))
print arr

给出

[[255 217 249 221  88]
 [ 28 207  85 219  85]
 [ 90 145 155 152  98]
 [196 121 228 101  92]
 [ 50 159  66 130   8]]

然后

img=Image.fromarray(arr,'L')
new_arr=np.array(img)

我希望 new_arr 与 arr 相同,但是

print new_arr
[[122   0   0   0   0]
 [  0   0   0  61   0]
 [  0   0   0   0   0]
 [  0 168   0   0   0]
 [  0   0   0   0 221]]

最佳答案

问题是 np.random.randint() 返回有符号 int,而 'L' 选项返回 Image.fromarray() 告诉它将数组解释为 8 位无符号 int ( PIL modes )。如果您显式地将其转换为 uint8 ,则它可以工作:

arr=np.random.randint(0,256,5*5)
arr.resize((5,5))
print arr

输出:

[[255 217 249 221  88]
 [ 28 207  85 219  85]
 [ 90 145 155 152  98]
 [196 121 228 101  92]
 [ 50 159  66 130   8]]

然后

img=Image.fromarray(arr.astype('uint8'),'L')  # cast to uint8
new_arr=np.array(img)
print new_arr

输出:

[[255 217 249 221  88]
 [ 28 207  85 219  85]
 [ 90 145 155 152  98]
 [196 121 228 101  92]
 [ 50 159  66 130   8]]

关于python - Image.fromarray(pixels) 和 np.array(img) 是否应该保持数据不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761266/

相关文章:

javascript - 如何获得纯色背景色和半透明叠加色的有效结果(6位十六进制值)?

python - beautifulsoup CSS Select - 查找其中不存在特定属性(ex 样式)的标签

python - 在自定义函数中实现轴参数

python - 属性错误 : 'numpy.ndarray' object has no attribute 'items'

python - 运行时错误: Too early to create image

python - 从图像中获取RGB数据并将其与相应像素写入CSV文件

创建矩阵时的 Python 错误

python - 如何使用 PIP 安装具有不同名称的 python 包

python - Python PIL 中的重叠多边形

python - 使用索引和值将值添加到 Scipy 稀疏矩阵