You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python提取图片元数据中的自定义用户属性(Keywords)

解决Python提取图片Keywords元数据的问题

你的现有代码依赖piexif库,但该库仅专注于读取EXIF标准的元数据,而图片的Keywords(关键词)通常存储在IPTC信息交换模型或XMP可扩展元数据平台中,这两类数据不在piexif的默认处理范围内,所以无法通过现有代码获取。

以下是两种可行的解决方案:

方案一:用Pillow读取IPTC中的Keywords

Pillow库支持读取IPTC元数据,Keywords在IPTC中对应的标签是2:25,可以通过以下代码提取:

from PIL import Image

def extract_keywords_from_iptc(image_path):
    with Image.open(image_path) as img:
        # 获取IPTC对应的IFD数据块
        iptc_ifd = img.getexif().get_ifd(0x83BB)
        keywords = []
        if iptc_ifd:
            # IPTC Keyword对应的标签ID是25
            for tag_id, value in iptc_ifd.items():
                if tag_id == 25:
                    # 部分情况下关键词以分号分隔,需拆分
                    keywords = value.split(';') if isinstance(value, str) else value
                    break
        return keywords

# 测试代码
image_name = 'D1241-118.jpg'
keywords = extract_keywords_from_iptc(image_name)
print(f"图片{image_name}的Keywords: {keywords}")

方案二:用exifread库读取多标准元数据

exifread库支持解析EXIF、IPTC、XMP三类元数据,兼容性更强,先安装库:

pip install exifread

然后用以下代码提取Keywords:

import exifread

def extract_keywords(image_path):
    with open(image_path, 'rb') as img_file:
        # 开启细节模式以读取IPTC和XMP
        tags = exifread.process_file(img_file, details=True)
        
        # 先尝试读取IPTC Keywords
        iptc_keywords = tags.get('Image Tag 0x19')
        if iptc_keywords:
            return iptc_keywords.values
        
        # 再尝试读取XMP中的Keywords(对应dc:subject字段)
        xmp_keywords = tags.get('XMP-dc:subject')
        if xmp_keywords:
            return xmp_keywords.values
        
        return []

# 测试代码
image_name = 'D1241-118.jpg'
keywords = extract_keywords(image_name)
print(f"图片{image_name}的Keywords: {keywords}")

说明:不同工具(如Photoshop、Lightroom)添加的Keywords可能存储在不同的元数据区域,建议两种方案都尝试,确保覆盖所有可能的存储位置。

内容的提问来源于stack exchange,提问作者Snir Ego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:07:45