我正在生成晶格的二进制配置,我想将它们另存为黑白图像。我在Python 3.7上使用以下代码:
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
L = 10
s = 2*np.random.randint(2, size=(L, L))-1
s = (s + 1) * 255/ 2
s.astype(np.uint8)
img = Image.fromarray(s, mode = 'L')
plt.imshow(img, cmap='gray')
plt.show()
img.save('test.jpg')
img2 = Image.open('test.jpg').convert('L')
data = asarray(img2).astype(int)
print(data)
这是我生成的随机数组:
[[255. 0. 0. 0. 0. 255. 255. 0. 0. 255.]
[ 0. 0. 0. 255. 0. 255. 0. 0. 255. 0.]
[ 0. 0. 0. 255. 255. 255. 0. 255. 0. 255.]
[255. 255. 255. 255. 255. 255. 0. 255. 255. 255.]
[255. 255. 0. 0. 0. 0. 255. 0. 255. 0.]
[255. 255. 0. 0. 255. 0. 255. 0. 0. 0.]
[ 0. 0. 255. 255. 0. 255. 255. 0. 0. 0.]
[ 0. 255. 0. 255. 0. 255. 255. 0. 255. 0.]
[ 0. 255. 0. 0. 255. 255. 255. 255. 255. 255.]
[ 0. 255. 0. 0. 255. 0. 255. 255. 0. 0.]]
但是代码输出的图像与我期望的完全不同。我得到的结果是以下图像,该图像似乎与该数组无关:
虽然我希望如此
我是通过在Mathematica中可视化数组获得的。请注意,在代码末尾,我保存并检索了图像。当我将其检索为数组时,获得
[[ 0 3 0 11 0 216 106 67 0 3]
[ 0 5 0 10 2 7 7 0 0 1]
[ 2 0 7 0 0 1 0 0 1 0]
[ 10 0 0 3 8 0 8 14 3 3]
[ 0 12 0 21 0 219 111 43 0 0]
[ 4 8 0 206 114 86 0 15 1 1]
[ 0 0 22 0 8 0 0 7 7 0]
[ 6 0 0 9 0 8 6 221 102 81]
[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]]
与原始数组s完全不同。如果有人能告诉我我做错了,我将不胜感激。
这是由于plt.imshow
使用的色图。默认情况下,它将以从深蓝色到亮黄色的颜色显示灰度图像。尝试添加一个可选参数,称为cmap:
plt.imshow(img ,cmap='gray')
有两个问题:
您将其另存为有损的JPEG-允许更改像素以节省空间。如果您关心像素是否正确保存,请使用无损格式,例如PNG
您没有保存更改dtype
的效果,因此您使用的变量仍然是浮点数-我在下面的代码中对其进行了注释
#!/usr/bin/env python3
import numpy as np
from PIL import Image
# Generate random but repeatable lattice
np.random.seed(42)
L = 10
s = 2*np.random.randint(2, size=(L, L))-1
s = (s + 1) * 255/ 2
sA = s.astype(np.uint8) # <--- YOUR CODE GOES WRONG HERE
# Now make into "PIL Image" and save as lossless PNG (not JPEG)
imA = Image.fromarray(sA)
imA.save('result.png')
imA.show()
# Now load back from disk
imB = Image.open('result.png')
sB = np.array(imB)
imB.show()
# Check we get the same Numpy array
if np.allclose(sA, sB):
print('Arrays are equal')
else:
print('ERROR: Arrays differ')