【问题标题】:In Python, how do I read the exif data for an image?在 Python 中,如何读取图像的 exif 数据?
【发布时间】:2011-06-13 11:46:01
【问题描述】:

我正在使用 PIL。如何将图片的EXIF数据转成字典?

【问题讨论】:

标签: python image python-imaging-library exif


【解决方案1】:

对于 Python3.x 并从 Pillow==6.0.0 开始,Image 对象现在提供“公共”/官方 getexif() 方法,该方法返回 <class 'PIL.Image.Exif'> 实例或 None(如果图像没有 EXIF 数据)。

来自Pillow 6.0.0 release notes

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

如上所述,您可以像普通字典一样迭代 Exif 实例的键值对。键是 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:
    for key, val in img_exif.items():
        if key in ExifTags.TAGS:
            print(f'{ExifTags.TAGS[key]}:{val}')
            # ExifVersion:b'0230'
            # ...
            # FocalLength:(2300, 100)
            # ColorSpace:1
            # ...
            # Model:'X-T2'
            # Make:'FUJIFILM'
            # LensSpecification:(18.0, 55.0, 2.8, 4.0)
            # ...
            # DateTime:'2019:12:01 21:30:07'
            # ...

使用 Python 3.8.8 和 Pillow==8.1.0 测试。

【讨论】:

  • 这对我不起作用,我只能看到使用二进制中的.info方法的exif数据
【解决方案2】:

读取图片网址并获取标签

from PIL import Image
from urllib.request import urlopen
from PIL.ExifTags import TAGS 


def get_exif(filename):
    image = Image.open(filename)
    image.verify()
    return image._getexif()

def get_labeled_exif(exif):
    labeled = {}
    for (key, val) in exif.items():
        labeled[TAGS.get(key)] = val

    return labeled

my_image= urlopen(url)

exif = get_exif(my_image)
labeled = get_labeled_exif(exif)
print(labeled)

要获取 GPS 坐标,Jayson DeLancey 有很棒的博文。

【讨论】:

    【解决方案3】:

    您可以使用 PIL 图像的 _getexif() 受保护方法。

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

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

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

    【讨论】:

    • 任何 Python 3 替代方案?
    • @2rs2ts:试试import ExifTags(不带PIL前缀)。
    • 对于 python3 使用 Pillow。是PIL的一个fork,还在开发中,有python3兼容版本
    • 这不适用于 python 3.x 并且 _get_exif 是受保护的方法,不应使用。
    【解决方案4】:

    我用这个:

    import os,sys
    from PIL import Image
    from PIL.ExifTags import TAGS
    
    for (k,v) in Image.open(sys.argv[1])._getexif().items():
            print('%s = %s' % (TAGS.get(k), v))
    

    或获取特定字段:

    def get_field (exif,field) :
      for (k,v) in exif.items():
         if TAGS.get(k) == field:
            return v
    
    exif = image._getexif()
    print get_field(exif,'ExposureTime')
    

    【讨论】:

    • 更好,你可以用name2tagnum = dict((name, num) for num, name in TAGS.iteritems())反转TAGS,然后用name2tagnum['ExposureTime']
    • 对于 Python 3,将 exif.iteritems() 更改为 exif.items()
    • 我们不应该使用私有方法_getexif。相反,Pillow 的方法getexif 更合适。
    【解决方案5】:

    我通常使用pyexiv2来设置JPG文件中的exif信息,但是当我在脚本中导入库时QGIS脚本崩溃了。

    我找到了使用库 exif 的解决方案:

    https://pypi.org/project/exif/

    它很容易使用,而且我没有使用 Qgis,没有任何问题。

    在这段代码中,我将 GPS 坐标插入到屏幕快照中:

    from exif import Image
    with open(file_name, 'rb') as image_file:
        my_image = Image(image_file)
    
    my_image.make = "Python"
    my_image.gps_latitude_ref=exif_lat_ref
    my_image.gps_latitude=exif_lat
    my_image.gps_longitude_ref= exif_lon_ref
    my_image.gps_longitude= exif_lon
    
    with open(file_name, 'wb') as new_image_file:
        new_image_file.write(my_image.get_file())
    

    【讨论】:

      【解决方案6】:
      import sys
      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 
      
      if __name__ == '__main__':
          try:
              img = PILimage.open(sys.argv[1])
              image = Worker(img)
              lat = image.lat
              lon = image.lon
              date = image.date
              print(date, lat, lon)
      
          except Exception as e:
              print(e)
      

      【讨论】:

        【解决方案7】:

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

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

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

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

        【讨论】:

        • info['parsed_exif'] 需要 Pillow 6.0 或更高版本。 info['exif'] 在 5.4 中可用,但这是一个原始字节串。
        • 7.0.0版本中没有info['parsed_exif'];只有info['exif']
        【解决方案8】:

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

        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
        

        【讨论】:

          【解决方案9】:

          您也可以使用ExifRead 模块:

          import exifread
          # Open image file for reading (binary mode)
          f = open(path_name, 'rb')
          
          # Return Exif tags
          tags = exifread.process_file(f)
          

          【讨论】:

          • 你能在这个问题上测试一下吗,下载图片,然后尝试获取 ImageDescription。 stackoverflow.com/questions/22173902/…
          • @Clayton 对于两个图像,exifread 返回空字典。但我对我的照片进行了测试,效果很好。
          • 我还收到了一组图像的空字典。任何人都可以评论为什么会这样吗? exifread.process_file() 可以处理什么样的图像?
          • @Momchill 这取决于图像文件。有些图像是在没有 EXIF 数据的情况下生成的。如果它以编程方式为空,请尝试在照片编辑软件中打开图像文件以检查它是否真的有 EXIF 数据。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-14
          • 1970-01-01
          • 1970-01-01
          • 2017-09-11
          • 2019-11-16
          • 1970-01-01
          • 2021-08-27
          相关资源
          最近更新 更多