【python】exif tag


import os

from PIL import Image
from PIL.ExifTags import TAGS,GPSTAGS
from os import path

class Point:
def __init__(self, lat, lon, alt, datetime):
self.lat = lat
self.lon = lon
self.alt = alt
self.datetime = datetime

def main():

files = os.listdir('/Users/mknod/git/ProblemMapping/exif_dec/images')

for file in files:

exif = {}
exif = getImageExif("images/" + file)

pt = getExifGps(exif)

print(pt.lon)
print(pt.lat)
print(pt.alt)
print(pt.datetime)

def getImageExif(filename):

image = Image.open(filename)

try:
exif = image._getexif()
return exif

except AttributeError:
return {}

def getExifGps(exif):

exif_data = {}
gpsinfo = {}
datetime = {}
lon_ref = 1
lat_ref = 1

pt = Point(None,None,None,None)

for tag, value in exif.items():

decoded = TAGS.get(tag, tag)

if decoded == "GPSInfo":

gps_data = {}
for t in value:

dec = GPSTAGS.get(t, t)
if dec == "GPSLongitude":
pt.lon = decimal_deg(value[t])
elif dec == "GPSLongitudeRef":
if value[t] == "W":
lon_ref = 1.0
elif value[t] == "E":
lon_ref = -1.0
elif dec == "GPSLatitudeRef":
if value[t] == "N":
lat_ref = 1.0
elif value[t] == "S":
lat_ref = -1.0
elif dec == "GPSLatitude":
pt.lat = decimal_deg(value[t])
pt.lat *= lat_ref
elif dec == "GPSAltitude":
pt.alt = value[t]

exif_data[decoded] = gps_data

elif decoded == "DateTime":
pt.datetime = value

return pt

def decimal_deg(coordinate):

hour, minute, second = coordinate
dec_hour = hour[0] * 1.0 / hour[1]
dec_min = minute[0] * 1.0 / minute[1] * 1.0 / 60.0
dec_sec = second[0] * 1.0 / second[1] * 1.0 / 60.0 / 60.0
dec_deg = dec_hour + dec_min + dec_sec

return dec_deg

# === main ===
main()

# {
# 'Flash': 0,
# 'Orientation': 0,
# 'ImageWidth': 3264,
# 'SubsecTimeDigitized': '077941\x00',
# 'JpegIFOffset': 482,
# 'ImageLength': 2448,
# 'Model': 'Nexus 5',
# 'DateTimeDigitized': '2015:02:27 11:40:57',
# 'WhiteBalance': 0,
# 'FocalLength': (3970, 1000),
# 'DateTime': '2015:02:27 11:40:57',
# 'LightSource': 0,
# 'Make': 'LGE',
# 'GPSInfo': {
# 1: 'N',
# 2: ((14, 1), (9, 1), (38626, 1000)),
# 3: 'E',
# 4: ((121, 1), (13, 1), (42257, 1000))
# },
# 'JpegIFByteCount': 38663,
# 'MeteringMode': 65535,
# 'SubsecTime': '077941\x00',
# 'ExifOffset': 452,
# 'SubsecTimeOriginal': '077941\x00'
# }

# ((14, 1), (9, 1), (38626, 1000)) = 14/1, 9/1, 38626/1000 = 14度9分38.626秒
# 14 + (9 / 60) + (38.626 / 60 / 60) = 14.16072944

# ((121, 1), (13, 1), (42257, 1000)) = 121/1, 13/1, 42257/1000 = 121度13分42.257秒

# 14.16072944,121.2284047

Leave a Reply