Python Pillow - 提取影像元資料



影像元資料指的是與數字影像相關聯的資訊。這些元資料可以包含各種詳細資訊,例如相機型號、拍攝日期和時間、位置資訊(GPS 座標)和關鍵詞。

在這種情況下,提取影像元資料是從影像中檢索這些底層資訊。一種廣泛使用的影像元資料型別是 EXIF 資料,它是“可交換影像檔案格式”的縮寫。這種標準化格式由佳能、美能達/索尼和尼康等組織建立,封裝了一套關於影像的綜合規範,包括相機設定、曝光引數等。

需要注意的是,所有 EXIF 資料都是元資料,但並非所有元資料都是 EXIF 資料。EXIF 是一種特定型別的元資料,您正在查詢的資料也可能屬於其他元資料型別,例如 IPTC 或 XMP 資料。

提取基本影像元資料

Python Pillow Image 物件提供了一種簡單的方法來訪問基本影像元資料,包括檔名、尺寸、格式、模式等。

示例

此示例演示瞭如何使用 Pillow Image 物件的屬性從影像中提取各種基本元資料。

from PIL import Image

# Path to the image
image_path = "Images/dance-cartoon.gif"

# Read the image data using Pillow
image = Image.open(image_path)

# Access and print basic image metadata
print("Filename:", image.filename)
print("Image Size:", image.size)
print("Image Height:", image.height)
print("Image Width:", image.width)
print("Image Format:", image.format)
print("Image Mode:", image.mode)

# Check if the image is animated (for GIF images)
if hasattr(image, "is_animated"):
   print("Image is Animated:", image.is_animated)
   print("Frames in Image:", image.n_frames)

輸出

Filename: Images/dance-cartoon.gif
Image Size: (370, 300)
Image Height: 300
Image Width: 370
Image Format: GIF
Image Mode: P
Image is Animated: True
Frames in Image: 12

提取高階影像元資料

Python Pillow 庫提供了訪問和管理影像元資料的工具,特別是透過Image.getexif()函式和ExifTags模組。

Image.getexif()函式從影像中檢索 EXIF 資料,其中包含大量關於影像的有價值的資訊。使用此函式的語法如下:

Image.getexif()

該函式返回一個 Exif 物件,此物件提供對 EXIF 影像資料的讀寫訪問。

PIL.ExifTags.TAGS字典用於解釋 EXIF 資料。此字典將 16 位整數 EXIF 標記列舉對映到人類可讀的描述性字串名稱,使元資料更容易理解。此字典的語法如下:

PIL.ExifTags.TAGS: dict

示例

以下示例演示瞭如何使用 Pillow 的getexif()方法訪問和列印影像檔案的 EXIF 元資料。它還展示瞭如何使用 TAGS 字典將標記 ID 對映到人類可讀的標記名稱。

from PIL import Image
from PIL.ExifTags import TAGS

# The path to the image 
image_path = "Images/flowers_canon.JPG"

# Open the image using the PIL library
image = Image.open(image_path)

# Extract EXIF data
exif_data = image.getexif()

# Iterate over all EXIF data fields
for tag_id, data in exif_data.items():
    
   # Get the tag name, instead of the tag ID
   tag_name = TAGS.get(tag_id, tag_id)
   print(f"{tag_name:25}: {data}")

輸出

GPSInfo                  : 10628
ResolutionUnit           : 2
ExifOffset               : 360
Make                     : Canon
Model                    : Canon EOS 80D
YResolution              : 72.0
Orientation              : 8
DateTime                 : 2020:10:25 15:39:08
YCbCrPositioning         : 2
Copyright                : CAMERAMAN_SAI
XResolution              : 72.0
Artist                   : CAMERAMAN_SAI
廣告