使用 PIL 保存带有特定 Tiff 标签的 Tiff

Saving Tiff with specific Tiff Tags using PIL

我正在尝试使用带有自定义标签的 PIL 保存 TIFF 图像。

import numpy as np
import PIL
numrows=10
numcols=10
data = np.random.randint(0, 255, (numrows,numcols)).astype(np.uint8)

rawtiff=PIL.Image.fromarray(data)

custtifftags={'Photometric':1, 'Compression':1, 'BitsPerSample':32,\
              'SamplePerPixel':1, 'SampleFormat':3,'ImageLength':10,\
              'ImageWidth':10, 'PlanarConfiguration':1, 'ResolutionUnit':2}

rawtiff.save('test.tiff', tiffinfo=custtifftags)

我收到以下错误:

TypeError: '<' not supported between instances of 'str' and 'int'

导致此错误的原因是什么?如何在设置自己的标签时使用 PIL 保存图像?

我明白了。您需要按如下方式格式化 TIFF 标签:

custtifftags={262:(1,), 259:(0,), 258:(32,),\
              277:(1,), 339:(3,),257:(10,),\
              256:(10,), 284:(1,), 296:(2,)}

TIFF 不按名称定义标签,仅按数值定义。 字母名称是为了方便起见。 在 TiffTags 中,您可以找到在 PIL 中使用的字母值。

作为解决方案,您可以尝试:

from PIL.TiffImagePlugin import ImageFileDirectory_v2
custtifftags = ImageFileDirectory_v2()
custtifftags[101] = 'Test Data 101'