我正在尝试使用 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,而Image.fromarray()
的'L'
选项告诉它将数组解释为 8 位无符号 int(PIL 模式)。如果您将其显式转换为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]]