Python PIL在未压缩的16位TIFF图像上遇到困难

2024-04-23 18:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的系统是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图像。我很惊讶这是如此困难,这使我相信这个问题将是显而易见的其他人。


Tags: 文档图像imageimportimgpilasshow
2条回答

原来Matplotlib在两行代码中处理16位未压缩的TIFF图像:

import matplotlib.pyplot as plt
img = plt.imread(filename)

# >>> img
# array([[38948, 41457, 37714, ..., 61511, 61785, 61824],
#       [39704, 38083, 36690, ..., 61419, 60086, 61910],
#       [41449, 39169, 38178, ..., 60192, 60969, 63538],
#       ...,
#       [37963, 39531, 40339, ..., 62351, 62646, 61793],
#       [37462, 37409, 38370, ..., 61125, 62497, 59770],
#       [39753, 36905, 38778, ..., 61922, 59565, 60035]], dtype=uint16)

等等。我想这不符合我的“轻量级”要求,因为Matplotlib(对我来说)是一个很重的模块,但是将图像放入Numpy数组非常简单。我希望这能帮助其他人尽快找到解决方案,因为这对我来说并不明显。

试试Pillow,“友好”的叉子。他们最近增加了对16位和32位图像的更好支持,包括在numpy数组接口中。此代码适用于最新的枕头:

from PIL import Image
import numpy as np

img = Image.open('data.tif')
data = np.array(img)

相关问题 更多 >