Replace/add 使用 Pillow 从一个文件到另一个文件的 Tiff 图像标签
Replace/add Tiff image tags using Pillow from one file to another
我是 python 的新手。我有两个 tiff 图像。一个标签正确 (source.tif
) 而另一个标签不正确 (target.tif
)。
我可以使用以下 python 脚本读取正确图像的标签。
from PIL import Image
from PIL.TiffTags import TAGS
Image.MAX_IMAGE_PIXELS = None
# open image
sourceimg = Image.open('images/source.tif')
# extract exif data
exifdata = sourceimg.getexif()
# get dictionary of tags
for tag_id in exifdata:
# get the tag name, instead of human unreadable tag id
tag = TAGS.get(tag_id, tag_id)
data = exifdata.get(tag_id)
# decode bytes
if isinstance(data, bytes):
data = data.decode()
print(f"{tag:25}: {data}")
如何从源代码中获取这些标签并且 overwrite/add 仅 target.tif
中的某些参数?
TiffImageFile.tag_v2
dict can be modified and used as the tiffinfo
argument when saving目标图片:
from PIL import Image
sourceimg = Image.open("source.tif")
targetimg = Image.open("target.tif")
# Get the TIFF tags from the source image
tiffinfo = sourceimg.tag_v2
# Add or modify any tags you want (using the tag number as key)
# Tag number 270 is the ImageDescription tag
tiffinfo[270] = "Example image"
# Save the target image with the correct tags
targetimg.save("target.tif", tiffinfo=tiffinfo)
print(targetimg.tag_v2[270])
>>> Example image
我是 python 的新手。我有两个 tiff 图像。一个标签正确 (source.tif
) 而另一个标签不正确 (target.tif
)。
我可以使用以下 python 脚本读取正确图像的标签。
from PIL import Image
from PIL.TiffTags import TAGS
Image.MAX_IMAGE_PIXELS = None
# open image
sourceimg = Image.open('images/source.tif')
# extract exif data
exifdata = sourceimg.getexif()
# get dictionary of tags
for tag_id in exifdata:
# get the tag name, instead of human unreadable tag id
tag = TAGS.get(tag_id, tag_id)
data = exifdata.get(tag_id)
# decode bytes
if isinstance(data, bytes):
data = data.decode()
print(f"{tag:25}: {data}")
如何从源代码中获取这些标签并且 overwrite/add 仅 target.tif
中的某些参数?
TiffImageFile.tag_v2
dict can be modified and used as the tiffinfo
argument when saving目标图片:
from PIL import Image
sourceimg = Image.open("source.tif")
targetimg = Image.open("target.tif")
# Get the TIFF tags from the source image
tiffinfo = sourceimg.tag_v2
# Add or modify any tags you want (using the tag number as key)
# Tag number 270 is the ImageDescription tag
tiffinfo[270] = "Example image"
# Save the target image with the correct tags
targetimg.save("target.tif", tiffinfo=tiffinfo)
print(targetimg.tag_v2[270])
>>> Example image