我正在使用PIL。如何将EXIF数据转换为字典?
答案 0 :(得分:144)
试试这个:
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
}
答案 1 :(得分:26)
您还可以使用ExifRead模块:
import exifread
# Open image file for reading (binary mode)
f = open(path_name, 'rb')
# Return Exif tags
tags = exifread.process_file(f)
答案 2 :(得分:14)
我用这个:
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)
或获取特定字段:
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')
答案 3 :(得分:3)
try:
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS
except ImportError as err:
exit(err)
class Worker(object):
def __init__(self, img):
self.img = img
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
self.exif_data = exif_data
# 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)
答案 4 :(得分:2)
这是可能更不容易阅读的一种。希望这会有所帮助。
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
答案 5 :(得分:0)
我发现使用._getexif
在更高版本的python中不起作用,而且,它是受保护的类,应该尽可能避免使用它。
深入研究调试器之后,这是我发现获取图像的EXIF数据的最佳方法:
from PIL import Image
def get_exif(path):
return Image.open(path).info['parsed_exif']
这将返回图像的所有EXIF数据的字典。
注意:对于Python3.x,请使用Pillow而不是PIL
答案 6 :(得分:0)
对于Python3.x和PIL(作为Pillow安装),Image
对象现在提供了一个getexif()
方法,如果图像没有EXIF数据,则该方法返回<class 'PIL.Image.Exif'>
或None
。 Exif
的输出可以通过强制转换简单地转换为dict
。
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:
print(dict(img_exif))
# { .. 271: 'FUJIFILM', 305: 'Adobe Photoshop Lightroom 6.14 (Macintosh)', }
img_exif_dict = dict(img_exif)
for key, val in img_exif_dict.items():
if key in ExifTags.TAGS:
print(f"{ExifTags.TAGS[key]}:{repr(val)}")
else:
print("Sorry, image has no exif data.")
已通过Python 3.6.8和Pillow==6.0.0
测试。
答案 7 :(得分:0)
我通常使用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())
答案 8 :(得分:0)
读取图片网址并获取标签
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 有很棒的博文。