在 Python 中,如何读取图像的 exif 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4764932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:25:06  来源:igfitidea点击:

In Python, how do I read the exif data for an image?

pythonimagepython-imaging-libraryexif

提问by TIMEX

I'm using PIL. How do I turn the EXIF data into a dictionary of stuff?

我正在使用 PIL。如何将 EXIF 数据转换为内容字典?

采纳答案by payne

Try this:

尝试这个:

import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()

This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like:

这应该会给你一个由 EXIF 数字标签索引的字典。如果您希望字典由实际的 EXIF 标签名称字符串索引,请尝试以下操作:

import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

回答by ianaré

You can also use the ExifReadmodule:

您还可以使用ExifRead模块:

import exifread
# Open image file for reading (binary mode)
f = open(path_name, 'rb')

# Return Exif tags
tags = exifread.process_file(f)

回答by Mike Redrobe

I use this:

我用这个:

import os,sys
from PIL import Image
from PIL.ExifTags import TAGS

for (k,v) in Image.open(sys.argv[1])._getexif().iteritems():
        print '%s = %s' % (TAGS.get(k), v)

or to get a specific field:

或获取特定字段:

def get_field (exif,field) :
  for (k,v) in exif.iteritems():
     if TAGS.get(k) == field:
        return v

exif = image._getexif()
print get_field(exif,'ExposureTime')

回答by Kirill Vladi

import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 


def main():
    date = image.date
    print(date)

if __name__ == '__main__':
    try:
        img = PILimage.open(path + filename)
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date)

    except Exception as e:
        print(e)

回答by Raj Stha

Here's the one that may be little easier to read. Hope this is helpful.

这是一个可能更容易阅读的内容。希望这是有帮助的。

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

回答by Param Kapur

I have found that using ._getexifdoesn't work in higher python versions, moreover, it is a protected class and one should avoid using it if possible. After digging around the debugger this is what I found to be the best way to get the EXIF data for an image:

我发现 using._getexif在更高的 python 版本中不起作用,而且,它是一个受保护的类,如果可能,应该避免使用它。在调试器周围挖掘之后,我发现这是获取图像 EXIF 数据的最佳方法:

from PIL import Image

def get_exif(path):
    return Image.open(path).info['parsed_exif']

This returns a dictionary of all the EXIF data of an image.

这将返回图像的所有 EXIF 数据的字典。

Note: For Python3.x use Pillow instead of PIL

注意:对于 Python3.x 使用 Pillow 而不是 PIL

回答by Gino Mempin

For Python3.x and starting Pillow==6.0.0, Imageobjects now provide a getexif()method that returns <class 'PIL.Image.Exif'>or Noneif the image has no EXIF data.

对于 Python3.x 和开始Pillow==6.0.0Image对象现在提供一个getexif()方法,用于返回<class 'PIL.Image.Exif'>或者None图像是否没有 EXIF 数据。

From Pillow 6.0.0 release notes:

来自Pillow 6.0.0 发行说明

getexif()has been added, which returns an Exifinstance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as an exifargument to include any changes in the output image.

getexif()已添加,它返回一个Exif实例。可以像字典一样检索和设置值。保存 JPEG、PNG 或 WEBP 时,可以将该实例作为exif参数传递以包含输出图像中的任何更改。

The Exifoutput can simply be casted to a dict, so that the EXIF data can then be accessed as regular key-value pairs of a dict. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGSmodule.

所述Exif输出可以被简单地浇铸到一个dict,从而使EXIF数据然后可以作为一个常规的键-值对被访问dict。键是 16 位整数,可以使用ExifTags.TAGS模块映射到它们的字符串名称。

from PIL import Image, ExifTags

img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>

if img_exif is None:
    print("Sorry, image has no exif data.")
else:
    img_exif_dict = dict(img_exif)
    print(img_exif_dict)
    # { ... 42035: 'FUJIFILM', 42036: 'XF23mmF2 R WR', 42037: '75A14188' ... }
    for key, val in img_exif_dict.items():
        if key in ExifTags.TAGS:
            print(f"{ExifTags.TAGS[key]}:{repr(val)}")
            # ExifVersion:b'0230'
            # ...
            # FocalLength:(2300, 100)
            # ColorSpace:1
            # FocalLengthIn35mmFilm:35
            # ...
            # Model:'X-T2'
            # Make:'FUJIFILM'
            # ...
            # DateTime:'2019:12:01 21:30:07'
            # ...

Tested with Python 3.6.8 and Pillow==6.0.0.

使用 Python 3.6.8 和Pillow==6.0.0.