如何使用 Python PIL 设置 TIFF 图像分辨率

how to set the TIFF image resolution with Python PIL

我使用以下脚本来设置 tiff 图像的分辨率:

from PIL import Image
im=Image.open('abc.bmp')
im.info
im=im.convert('1')
im.info
im.save('abc.tif')

因为我可以清楚地看到图像的分辨率是 ('dpi': (300, 300)),所以我假设输出的 TIFF 图像应该具有 300 DPI 的分辨率。但是,当我读取 TIFF 文件的头文件信息时,输出分辨率未定义。关于设置分辨率的任何想法?谢谢

我使用 ImageMagick 的 identify 程序读取文件元数据。我的源文件是 venerable Lena image 其中:

$ identify -verbose lena.jpg
…
Resolution: 72x72
…

其中分辨率包含在 JFIF 块中。 PIL† 似乎没有在 Image.open:

中翻译这个 JFIF 块
>>> im = Image.open('lena.jpg')
>>> im.info 
{'exif': b'Exif\x00\x00II*\x00\x08…',
 'jfif': 257,
 'jfif_density': (1, 1),
 'jfif_unit': 0,
 'jfif_version': (1, 1)}

但是,您可以为 TIFF 输出指定分辨率

>>> im.save('lena.tiff', dpi=(300, 300))
>>> lena = Image.open('lena.tiff')
>>> lena.info
{'compression': 'raw', 'dpi': (300.0, 300.0)}

identify同意

$ identify -verbose lena.tiff
…
  Resolution: 300x300
…

†关于 PIL 明显死亡的注释

据我所知,last release of PIL was in 2009 which was supplanted by the Pillow Project which appears to be in active development。不幸的是,Pillow 没有更改包名,所以如果你写:

import PIL

from PIL import Image

除了

你知道你正在使用哪个库的方法
>>> PIL.PILLOW_VERSION 

在 PIL 下应该会产生 NameError,但在 Pillow 下会产生版本号(“2.9.0”是最新版本)。

如果你使用的是 PIL,而不是 Pillow,我不知道上面的答案是否适合你,而且我已经达到了我今天想阅读多少 PIL-ish 代码的限制。