我一直在使用版本为5.3.0的PIL处理这张图片:
![enter image description here](https://istack.dev59.com/ohPOx.webp)
它可以很好地读取数据:
>>> image = Image.open('/home/jcomeau/Downloads/grayscale_example.png')
>>> image.mode
'I'
>>> image.getextrema()
(5140, 62708)
>>> image.save('/tmp/test.png')
并且它以正确的模式保存,但是内容并不完全相同:
jcomeau@aspire:~$ diff /tmp/test.png ~/Downloads/grayscale_example.png
Binary files /tmp/test.png and /home/jcomeau/Downloads/grayscale_example.png differ
jcomeau@aspire:~$ identify /tmp/test.png ~/Downloads/grayscale_example.png
/tmp/test.png PNG 85x63 85x63+0+0 16-bit sRGB 6.12KB 0.010u 0:00.000
/home/jcomeau/Downloads/grayscale_example.png PNG 85x63 85x63+0+0 16-bit sRGB 6.14KB 0.000u 0:00.000
然而,image.show()
总是转换为 8 位灰度图像,被夹在 0 和 255 之间。因此,在任何转换阶段查看所得到的结果都是无用的。虽然我可以编写一个程序来实现这一点,甚至可能通过猴子补丁的方式修改 .show()
,但我只需在另一个 xterm 中运行 display
命令即可。
>>> image.putdata([n - 32768 for n in image.getdata()])
>>> image.getextrema()
(-27628, 29940)
>>> image.save('/tmp/test2.png')
![darkened grayscale image](https://istack.dev59.com/XVlty.webp)
请注意,转换为模式
I;16
也没有帮助:
>>> image.convert('I;16').save('/tmp/test3.png')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jcomeau/.local/lib/python2.7/site-packages/PIL/Image.py", line 1969, in save
save_handler(self, fp, filename)
File "/home/jcomeau/.local/lib/python2.7/site-packages/PIL/PngImagePlugin.py", line 729, in _save
raise IOError("cannot write mode %s as PNG" % mode)
IOError: cannot write mode I;16 as PNG