Created
September 9, 2016 05:41
-
-
Save dufferzafar/f455099332ade457599cf97070a930b6 to your computer and use it in GitHub Desktop.
Read position data from EXIF tags of images.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from PIL import Image | |
from PIL.ExifTags import TAGS, GPSTAGS | |
def get_exif_data(image): | |
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" | |
exif_data = {} | |
info = image._getexif() | |
if info: | |
for tag, value in info.items(): | |
decoded = TAGS.get(tag, tag) | |
if decoded == "GPSInfo": | |
gps_data = {} | |
for gps_tag in value: | |
sub_decoded = GPSTAGS.get(gps_tag, gps_tag) | |
gps_data[sub_decoded] = value[gps_tag] | |
exif_data[decoded] = gps_data | |
else: | |
exif_data[decoded] = value | |
return exif_data | |
def _convert_to_degress(value): | |
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format""" | |
deg_num, deg_denom = value[0] | |
d = float(deg_num) / float(deg_denom) | |
min_num, min_denom = value[1] | |
m = float(min_num) / float(min_denom) | |
sec_num, sec_denom = value[2] | |
s = float(sec_num) / float(sec_denom) | |
return d + (m / 60.0) + (s / 3600.0) | |
def get_lat_lon(exif_data): | |
"""Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)""" | |
lat = None | |
lon = None | |
if "GPSInfo" in exif_data: | |
gps_info = exif_data["GPSInfo"] | |
gps_latitude = gps_info.get("GPSLatitude") | |
gps_latitude_ref = gps_info.get('GPSLatitudeRef') | |
gps_longitude = gps_info.get('GPSLongitude') | |
gps_longitude_ref = gps_info.get('GPSLongitudeRef') | |
if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref: | |
lat = _convert_to_degress(gps_latitude) | |
if gps_latitude_ref != "N": | |
lat *= -1 | |
lon = _convert_to_degress(gps_longitude) | |
if gps_longitude_ref != "E": | |
lon *= -1 | |
return lat, lon | |
################ | |
# Example ###### | |
################ | |
if __name__ == "__main__": | |
# load an image through PIL's Image object | |
if len(sys.argv) < 2: | |
print("Error! No image file specified!") | |
print("Usage: %s <filename>" % sys.argv[0]) | |
sys.exit(1) | |
image = Image.open(sys.argv[1]) | |
exif_data = get_exif_data(image) | |
print(get_lat_lon(exif_data)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime as dt | |
from collections import OrderedDict | |
from glob import glob | |
from sys import argv | |
from PIL import Image | |
from PIL.ExifTags import TAGS, GPSTAGS | |
def get_exif_data(image): | |
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" | |
info = image._getexif() | |
if not info: | |
return {} | |
exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()} | |
def is_fraction(val): | |
return isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], int) and isinstance(val[1], int) | |
def frac_to_dec(frac): | |
return float(frac[0]) / float(frac[1]) | |
if "GPSInfo" in exif_data: | |
gpsinfo = {GPSTAGS.get(t, t): v for t, v in exif_data["GPSInfo"].items()} | |
for tag, value in gpsinfo.items(): | |
if is_fraction(value): | |
gpsinfo[tag] = frac_to_dec(value) | |
elif all(is_fraction(x) for x in value): | |
gpsinfo[tag] = tuple(map(frac_to_dec, value)) | |
exif_data["GPSInfo"] = gpsinfo | |
return exif_data | |
def get_lat_lon(exif_data): | |
"""Returns the latitude and longitude, if available, from the provided exif_data""" | |
lat = None | |
lon = None | |
gps_info = exif_data.get("GPSInfo") | |
def convert_to_degrees(value): | |
d, m, s = value | |
return d + (m / 60.0) + (s / 3600.0) | |
if gps_info: | |
gps_latitude = gps_info.get("GPSLatitude") | |
gps_latitude_ref = gps_info.get("GPSLatitudeRef") | |
gps_longitude = gps_info.get("GPSLongitude") | |
gps_longitude_ref = gps_info.get("GPSLongitudeRef") | |
if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref: | |
lat = convert_to_degrees(gps_latitude) | |
if gps_latitude_ref != "N": | |
lat = -lat | |
lon = convert_to_degrees(gps_longitude) | |
if gps_longitude_ref != "E": | |
lon = -lon | |
return lat, lon | |
def get_gps_datetime(exif_data): | |
"""Returns the timestamp, if available, from the provided exif_data""" | |
if "GPSInfo" not in exif_data: | |
return None | |
gps_info = exif_data["GPSInfo"] | |
date_str = gps_info.get("GPSDateStamp") | |
time = gps_info.get("GPSTimeStamp") | |
if not date_str or not time: | |
return None | |
date = map(int, date_str.split(":")) | |
timestamp = [date, map(int, time)] | |
timestamp += [int((time[2] % 1) * 1e6)] # microseconds | |
return dt.datetime(*timestamp) | |
def clean_gps_info(exif_data): | |
"""Return GPS EXIF info in a more convenient format from the provided exif_data""" | |
gps_info = exif_data["GPSInfo"] | |
cleaned = OrderedDict() | |
cleaned["Latitude"], cleaned["Longitude"] = get_lat_lon(exif_data) | |
cleaned["Altitude"] = gps_info.get("GPSAltitude") | |
cleaned["Speed"] = gps_info.get("GPSSpeed") | |
cleaned["SpeedRef"] = gps_info.get("GPSSpeedRef") | |
cleaned["Track"] = gps_info.get("GPSTrack") | |
cleaned["TrackRef"] = gps_info.get("GPSTrackRef") | |
cleaned["TimeStamp"] = get_gps_datetime(exif_data) | |
return cleaned | |
if __name__ == "__main__": | |
if len(argv) < 2: | |
print("Usage:\n\t{} image1 [image2 [...]]".format(argv[0])) | |
imgs = [] | |
for img in argv[1:]: | |
imgs += list(glob(img)) | |
print("file\tx\ty\tz\tdirection\tspeed\ttime") | |
for img in imgs: | |
with Image.open(img) as image: | |
exif_data = get_exif_data(image) | |
gps_info = clean_gps_info(exif_data) | |
print("{}\t{Longitude:.6f}\t{Latitude:.6f}\t{Altitude:.3f}\t{Track:3.3f}\t{Speed}\t{TimeStamp}".format( | |
img, **gps_info)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment