Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get GPS coordinates, direction, speed and timestamp from EXIF using PIL
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))
<!DOCTYPE qgis-layer-definition>
<!-- Sample QGIS layer definition file to display the output of get_exif_gps_info.py as a layer.
Set the qlr/maplayers/maplayer/datasource element to the generated file's location -->
<qlr>
<maplayers>
<maplayer geometry="Point" type="vector">
<id>locations20151127190740953</id>
<!-- Replace locations.txt with your own generated file's location -->
<datasource>locations.txt?type=csv&amp;delimiter=%5Ct&amp;xField=x&amp;yField=y&amp;spatialIndex=no&amp;subsetIndex=no&amp;watchFile=no</datasource>
<title>image locations</title>
<layername>image locations</layername>
<srs>
<spatialrefsys>
<proj4>+proj=longlat +datum=WGS84 +no_defs</proj4>
<srsid>3452</srsid>
<srid>4326</srid>
<authid>EPSG:4326</authid>
<description>WGS 84</description>
<projectionacronym>longlat</projectionacronym>
<ellipsoidacronym>WGS84</ellipsoidacronym>
<geographicflag>true</geographicflag>
</spatialrefsys>
</srs>
<provider encoding="UTF-8">delimitedtext</provider>
<edittypes>
<edittype widgetv2type="TextEdit" name="file">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="x">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="y">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="z">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="direction">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="speed">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
<edittype widgetv2type="TextEdit" name="time">
<widgetv2config IsMultiline="0" fieldEditable="1" UseHtml="0" labelOnTop="0"/>
</edittype>
</edittypes>
<renderer-v2 symbollevels="0" type="singleSymbol">
<symbols>
<symbol alpha="1" clip_to_extent="1" type="marker" name="0">
<layer pass="0" class="SimpleMarker" locked="0">
<prop k="angle" v="0"/>
<prop k="angle_dd_active" v="1"/>
<prop k="angle_dd_expression" v=""/>
<prop k="angle_dd_field" v="direction"/>
<prop k="angle_dd_useexpr" v="0"/>
<prop k="color" v="255,251,0,255"/>
<prop k="horizontal_anchor_point" v="1"/>
<prop k="name" v="arrow"/>
<prop k="offset" v="0,0"/>
<prop k="offset_map_unit_scale" v="0,0"/>
<prop k="offset_unit" v="MM"/>
<prop k="outline_color" v="0,0,0,255"/>
<prop k="outline_style" v="solid"/>
<prop k="outline_width" v="0"/>
<prop k="outline_width_map_unit_scale" v="0,0"/>
<prop k="outline_width_unit" v="MM"/>
<prop k="scale_method" v="area"/>
<prop k="size" v="4"/>
<prop k="size_dd_active" v="0"/>
<prop k="size_dd_expression" v=""/>
<prop k="size_dd_field" v="speed"/>
<prop k="size_dd_useexpr" v="0"/>
<prop k="size_map_unit_scale" v="0,0"/>
<prop k="size_unit" v="MM"/>
<prop k="vertical_anchor_point" v="1"/>
<effect enabled="0" type="effectStack">
<effect type="dropShadow">
<prop k="blend_mode" v="13"/>
<prop k="blur_level" v="10"/>
<prop k="color" v="0,0,0,255"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="offset_angle" v="135"/>
<prop k="offset_distance" v="2"/>
<prop k="offset_unit" v="MM"/>
<prop k="offset_unit_scale" v="0,0"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="outerGlow">
<prop k="blend_mode" v="0"/>
<prop k="blur_level" v="3"/>
<prop k="color_type" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="single_color" v="255,255,255,255"/>
<prop k="spread" v="2"/>
<prop k="spread_unit" v="MM"/>
<prop k="spread_unit_scale" v="0,0"/>
<prop k="transparency" v="0.5"/>
</effect>
<effect type="drawSource">
<prop k="blend_mode" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="1"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="innerShadow">
<prop k="blend_mode" v="13"/>
<prop k="blur_level" v="10"/>
<prop k="color" v="0,0,0,255"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="offset_angle" v="135"/>
<prop k="offset_distance" v="2"/>
<prop k="offset_unit" v="MM"/>
<prop k="offset_unit_scale" v="0,0"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="innerGlow">
<prop k="blend_mode" v="0"/>
<prop k="blur_level" v="3"/>
<prop k="color_type" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="single_color" v="255,255,255,255"/>
<prop k="spread" v="2"/>
<prop k="spread_unit" v="MM"/>
<prop k="spread_unit_scale" v="0,0"/>
<prop k="transparency" v="0.5"/>
</effect>
</effect>
</layer>
</symbol>
</symbols>
<rotation/>
<sizescale scalemethod="diameter"/>
<effect enabled="0" type="effectStack">
<effect type="dropShadow">
<prop k="blend_mode" v="13"/>
<prop k="blur_level" v="10"/>
<prop k="color" v="0,0,0,255"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="offset_angle" v="135"/>
<prop k="offset_distance" v="2"/>
<prop k="offset_unit" v="MM"/>
<prop k="offset_unit_scale" v="0,0"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="outerGlow">
<prop k="blend_mode" v="0"/>
<prop k="blur_level" v="3"/>
<prop k="color_type" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="single_color" v="255,255,255,255"/>
<prop k="spread" v="2"/>
<prop k="spread_unit" v="MM"/>
<prop k="spread_unit_scale" v="0,0"/>
<prop k="transparency" v="0.5"/>
</effect>
<effect type="drawSource">
<prop k="blend_mode" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="1"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="innerShadow">
<prop k="blend_mode" v="13"/>
<prop k="blur_level" v="10"/>
<prop k="color" v="0,0,0,255"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="offset_angle" v="135"/>
<prop k="offset_distance" v="2"/>
<prop k="offset_unit" v="MM"/>
<prop k="offset_unit_scale" v="0,0"/>
<prop k="transparency" v="0"/>
</effect>
<effect type="innerGlow">
<prop k="blend_mode" v="0"/>
<prop k="blur_level" v="3"/>
<prop k="color_type" v="0"/>
<prop k="draw_mode" v="2"/>
<prop k="enabled" v="0"/>
<prop k="single_color" v="255,255,255,255"/>
<prop k="spread" v="2"/>
<prop k="spread_unit" v="MM"/>
<prop k="spread_unit_scale" v="0,0"/>
<prop k="transparency" v="0.5"/>
</effect>
</effect>
</renderer-v2>
<customproperties>
<property key="labeling" value="pal"/>
<property key="labeling/addDirectionSymbol" value="false"/>
<property key="labeling/angleOffset" value="0"/>
<property key="labeling/blendMode" value="0"/>
<property key="labeling/bufferBlendMode" value="0"/>
<property key="labeling/bufferColorA" value="255"/>
<property key="labeling/bufferColorB" value="255"/>
<property key="labeling/bufferColorG" value="255"/>
<property key="labeling/bufferColorR" value="255"/>
<property key="labeling/bufferDraw" value="false"/>
<property key="labeling/bufferJoinStyle" value="64"/>
<property key="labeling/bufferNoFill" value="false"/>
<property key="labeling/bufferSize" value="1"/>
<property key="labeling/bufferSizeInMapUnits" value="false"/>
<property key="labeling/bufferSizeMapUnitMaxScale" value="0"/>
<property key="labeling/bufferSizeMapUnitMinScale" value="0"/>
<property key="labeling/bufferTransp" value="0"/>
<property key="labeling/centroidInside" value="false"/>
<property key="labeling/centroidWhole" value="false"/>
<property key="labeling/decimals" value="3"/>
<property key="labeling/displayAll" value="false"/>
<property key="labeling/dist" value="1"/>
<property key="labeling/distInMapUnits" value="false"/>
<property key="labeling/distMapUnitMaxScale" value="0"/>
<property key="labeling/distMapUnitMinScale" value="0"/>
<property key="labeling/enabled" value="true"/>
<property key="labeling/fieldName" value="file"/>
<property key="labeling/fontBold" value="false"/>
<property key="labeling/fontCapitals" value="0"/>
<property key="labeling/fontFamily" value="MS Shell Dlg 2"/>
<property key="labeling/fontItalic" value="false"/>
<property key="labeling/fontLetterSpacing" value="0"/>
<property key="labeling/fontLimitPixelSize" value="false"/>
<property key="labeling/fontMaxPixelSize" value="10000"/>
<property key="labeling/fontMinPixelSize" value="3"/>
<property key="labeling/fontSize" value="8"/>
<property key="labeling/fontSizeInMapUnits" value="false"/>
<property key="labeling/fontSizeMapUnitMaxScale" value="0"/>
<property key="labeling/fontSizeMapUnitMinScale" value="0"/>
<property key="labeling/fontStrikeout" value="false"/>
<property key="labeling/fontUnderline" value="false"/>
<property key="labeling/fontWeight" value="50"/>
<property key="labeling/fontWordSpacing" value="0"/>
<property key="labeling/formatNumbers" value="false"/>
<property key="labeling/isExpression" value="false"/>
<property key="labeling/labelOffsetInMapUnits" value="true"/>
<property key="labeling/labelOffsetMapUnitMaxScale" value="0"/>
<property key="labeling/labelOffsetMapUnitMinScale" value="0"/>
<property key="labeling/labelPerPart" value="false"/>
<property key="labeling/leftDirectionSymbol" value="&lt;"/>
<property key="labeling/limitNumLabels" value="false"/>
<property key="labeling/maxCurvedCharAngleIn" value="20"/>
<property key="labeling/maxCurvedCharAngleOut" value="-20"/>
<property key="labeling/maxNumLabels" value="2000"/>
<property key="labeling/mergeLines" value="false"/>
<property key="labeling/minFeatureSize" value="0"/>
<property key="labeling/multilineAlign" value="0"/>
<property key="labeling/multilineHeight" value="1"/>
<property key="labeling/namedStyle" value="Normal"/>
<property key="labeling/obstacle" value="true"/>
<property key="labeling/placeDirectionSymbol" value="0"/>
<property key="labeling/placement" value="0"/>
<property key="labeling/placementFlags" value="0"/>
<property key="labeling/plussign" value="false"/>
<property key="labeling/preserveRotation" value="true"/>
<property key="labeling/previewBkgrdColor" value="#ffffff"/>
<property key="labeling/priority" value="5"/>
<property key="labeling/quadOffset" value="4"/>
<property key="labeling/repeatDistance" value="0"/>
<property key="labeling/repeatDistanceMapUnitMaxScale" value="0"/>
<property key="labeling/repeatDistanceMapUnitMinScale" value="0"/>
<property key="labeling/repeatDistanceUnit" value="1"/>
<property key="labeling/reverseDirectionSymbol" value="false"/>
<property key="labeling/rightDirectionSymbol" value=">"/>
<property key="labeling/scaleMax" value="10000000"/>
<property key="labeling/scaleMin" value="1"/>
<property key="labeling/scaleVisibility" value="false"/>
<property key="labeling/shadowBlendMode" value="6"/>
<property key="labeling/shadowColorB" value="0"/>
<property key="labeling/shadowColorG" value="0"/>
<property key="labeling/shadowColorR" value="0"/>
<property key="labeling/shadowDraw" value="true"/>
<property key="labeling/shadowOffsetAngle" value="135"/>
<property key="labeling/shadowOffsetDist" value="1"/>
<property key="labeling/shadowOffsetGlobal" value="true"/>
<property key="labeling/shadowOffsetMapUnitMaxScale" value="0"/>
<property key="labeling/shadowOffsetMapUnitMinScale" value="0"/>
<property key="labeling/shadowOffsetUnits" value="1"/>
<property key="labeling/shadowRadius" value="1.5"/>
<property key="labeling/shadowRadiusAlphaOnly" value="false"/>
<property key="labeling/shadowRadiusMapUnitMaxScale" value="0"/>
<property key="labeling/shadowRadiusMapUnitMinScale" value="0"/>
<property key="labeling/shadowRadiusUnits" value="1"/>
<property key="labeling/shadowScale" value="100"/>
<property key="labeling/shadowTransparency" value="30"/>
<property key="labeling/shadowUnder" value="0"/>
<property key="labeling/shapeBlendMode" value="0"/>
<property key="labeling/shapeBorderColorA" value="255"/>
<property key="labeling/shapeBorderColorB" value="128"/>
<property key="labeling/shapeBorderColorG" value="128"/>
<property key="labeling/shapeBorderColorR" value="128"/>
<property key="labeling/shapeBorderWidth" value="0"/>
<property key="labeling/shapeBorderWidthMapUnitMaxScale" value="0"/>
<property key="labeling/shapeBorderWidthMapUnitMinScale" value="0"/>
<property key="labeling/shapeBorderWidthUnits" value="1"/>
<property key="labeling/shapeDraw" value="false"/>
<property key="labeling/shapeFillColorA" value="255"/>
<property key="labeling/shapeFillColorB" value="255"/>
<property key="labeling/shapeFillColorG" value="255"/>
<property key="labeling/shapeFillColorR" value="255"/>
<property key="labeling/shapeJoinStyle" value="64"/>
<property key="labeling/shapeOffsetMapUnitMaxScale" value="0"/>
<property key="labeling/shapeOffsetMapUnitMinScale" value="0"/>
<property key="labeling/shapeOffsetUnits" value="1"/>
<property key="labeling/shapeOffsetX" value="0"/>
<property key="labeling/shapeOffsetY" value="0"/>
<property key="labeling/shapeRadiiMapUnitMaxScale" value="0"/>
<property key="labeling/shapeRadiiMapUnitMinScale" value="0"/>
<property key="labeling/shapeRadiiUnits" value="1"/>
<property key="labeling/shapeRadiiX" value="0"/>
<property key="labeling/shapeRadiiY" value="0"/>
<property key="labeling/shapeRotation" value="0"/>
<property key="labeling/shapeRotationType" value="0"/>
<property key="labeling/shapeSVGFile" value=""/>
<property key="labeling/shapeSizeMapUnitMaxScale" value="0"/>
<property key="labeling/shapeSizeMapUnitMinScale" value="0"/>
<property key="labeling/shapeSizeType" value="0"/>
<property key="labeling/shapeSizeUnits" value="1"/>
<property key="labeling/shapeSizeX" value="0"/>
<property key="labeling/shapeSizeY" value="0"/>
<property key="labeling/shapeTransparency" value="0"/>
<property key="labeling/shapeType" value="0"/>
<property key="labeling/textColorA" value="255"/>
<property key="labeling/textColorB" value="255"/>
<property key="labeling/textColorG" value="255"/>
<property key="labeling/textColorR" value="255"/>
<property key="labeling/textTransp" value="0"/>
<property key="labeling/upsidedownLabels" value="0"/>
<property key="labeling/wrapChar" value=""/>
<property key="labeling/xOffset" value="0"/>
<property key="labeling/yOffset" value="0"/>
</customproperties>
<blendMode>0</blendMode>
<featureBlendMode>0</featureBlendMode>
<layerTransparency>0</layerTransparency>
<displayfield>file</displayfield>
<label>0</label>
<labelattributes>
<label fieldname="" text=""/>
<family fieldname="" name="MS Shell Dlg 2"/>
<size fieldname="" units="pt" value="12"/>
<bold fieldname="" on="0"/>
<italic fieldname="" on="0"/>
<underline fieldname="" on="0"/>
<strikeout fieldname="" on="0"/>
<color fieldname="" red="0" blue="0" green="0"/>
<x fieldname=""/>
<y fieldname=""/>
<offset x="0" y="0" units="pt" yfieldname="" xfieldname=""/>
<angle fieldname="" value="0" auto="0"/>
<alignment fieldname="" value="center"/>
<buffercolor fieldname="" red="255" blue="255" green="255"/>
<buffersize fieldname="" units="pt" value="1"/>
<bufferenabled fieldname="" on=""/>
<multilineenabled fieldname="" on=""/>
<selectedonly on=""/>
</labelattributes>
<SingleCategoryDiagramRenderer diagramType="Pie">
<DiagramCategory penColor="#000000" labelPlacementMethod="XHeight" penWidth="0" diagramOrientation="Up" minimumSize="0" barWidth="5" penAlpha="255" maxScaleDenominator="1e+08" backgroundColor="#ffffff" transparency="0" width="15" scaleDependency="Area" backgroundAlpha="255" angleOffset="1440" scaleBasedVisibility="0" enabled="0" height="15" sizeType="MM" minScaleDenominator="0">
<fontProperties description="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" style=""/>
</DiagramCategory>
</SingleCategoryDiagramRenderer>
<DiagramLayerSettings yPosColumn="-1" linePlacementFlags="10" placement="0" dist="0" xPosColumn="-1" priority="0" obstacle="0" showAll="1"/>
<editform></editform>
<editforminit/>
<featformsuppress>0</featformsuppress>
<annotationform></annotationform>
<editorlayout>generatedlayout</editorlayout>
<excludeAttributesWMS/>
<excludeAttributesWFS/>
<attributeactions/>
</maplayer>
</maplayers>
</qlr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment