#!/usr/bin/env python
#######################################################################################
#
# DeltaTag: enhanced geo-referencing survey images
# @author: Sander Smeets (sander@droneslab.com)
# Copyright (c) 2018 Vertical Technologies
#
# DeltaTag provides an alternate method to geo-referencing images from survey missions.
# It uses the delta in seconds between the images and the delta between the triggers to 
# match geo information with pictures, allowing for missing images.
#
# It uses the last image and last trigger event as a calibration point as errors are
# more likely to arrise in the first images (test triggers, booting cameras, etc)
# 
# Note: DeltaTag does not make copies, it writes the Exif information directly to the images
#
# Install: pip install pyulog piexif Pillow numpy
# Run: python geotag_images_ulog.py [logfile] [image dir] (optional offset)
# eg: python geotag_images_ulog.py mylog.ulg ./images
#
# Parameters
# logfile: a ulog formatted logfile containing camera_capture events (survey missions)
# image_dir: the directory where the images are located
# offset (optional): skip [offset] triggers to reference the last image
#                    0 means the last trigger event equals last image (default)
#                    1 means the second last trigger event equals last image
#                    ...etc
#
# Parts included from https://gist.github.com/c060604/8a51f8999be12fc2be498e9ca56adc72
# Parts included from https://github.com/PX4/flight_review/


import os, sys, time, datetime, piexif
from pyulog import *
from pyulog.px4 import *
from PIL import Image
from fractions import Fraction


if(len(sys.argv)) < 3:
    print "Usage: python geotag_images_ulog.py [logfile] [image dir]"
    print "Example: python geotag_images_ulog.py mylog.ulg ./images"
    print len(sys.argv)
    sys.exit()

logfile = sys.argv[1]
imageDir = sys.argv[2]
triggerOffset = 0

if(len(sys.argv) > 3):
    triggerOffset = int(sys.argv[3])