我的系统是MacOSXV10.8.2。我有几个2560x500未压缩的16位TIFF图像(灰度,无符号16位整数)。我首先尝试使用PIL(通过自制版本1.7.8安装)加载它们:
from PIL import Image
import numpy as np
filename = 'Rocks_2ptCal_750KHz_20ms_1ma_120KV_2013-03-06_20-02-12.tif'
img = Image.open(filename)
# >>> img
# <PIL.TiffImagePlugin.TiffImageFile image mode=I;16B size=2560x500 at 0x10A383C68>
img.show()
# almost all pixels displayed as white. Not correct.
# MatLab, EZ-draw, even Mac Preview show correct images in grayscale.
imgdata = list(img.getdata())
# most values negative:
# >>> imgdata[0:10]
# [-26588, -24079, -27822, -26045, -27245, -25368, -26139, -28454, -30675, -28455]
imgarray = np.asarray(imgdata, dtype=np.uint16)
# values now correct
# >>> imgarray
# array([38948, 41457, 37714, ..., 61922, 59565, 60035], dtype=uint16)
负值关闭65536。。。可能不是巧合。
如果我假装改变像素并通过PIL恢复为TIFF图像(只需将数组作为图像放回去):
newimg = Image.fromarray(imgarray)
我得到错误:
File "/usr/local/lib/python2.7/site-packages/PIL/Image.py", line 1884, in fromarray
raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type
在PIL文档中找不到Image.fromarray()
。我试过通过Image.fromstring()
加载,但是我不理解PIL文档,而且几乎没有示例。
如上面的代码所示,PIL似乎将数据“检测”为I;16B
。从PIL文档中我可以看出,模式I
:
*I* (32-bit signed integer pixels)
显然,这是不对的。
我发现SX上有很多帖子暗示PIL不支持16位图像。我找到了使用pylibtiff的建议,但我相信那只是Windows?
我正在寻找一种“轻量级”的方法来处理Python中的这些TIFF图像。我很惊讶这是如此困难,这使我相信这个问题将是显而易见的其他人。
原来Matplotlib在两行代码中处理16位未压缩的TIFF图像:
等等。我想这不符合我的“轻量级”要求,因为Matplotlib(对我来说)是一个很重的模块,但是将图像放入Numpy数组非常简单。我希望这能帮助其他人尽快找到解决方案,因为这对我来说并不明显。
试试Pillow,“友好”的叉子。他们最近增加了对16位和32位图像的更好支持,包括在numpy数组接口中。此代码适用于最新的枕头:
相关问题 更多 >
编程相关推荐