forked from ArduPilot/MissionPlanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeorefimage.cs
1913 lines (1502 loc) · 75.8 KB
/
georefimage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Windows.Forms;
using com.drew.imaging.jpg;
using com.drew.imaging.tiff;
using com.drew.metadata;
using log4net;
using SharpKml.Base;
using SharpKml.Dom;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Globalization;
namespace MissionPlanner
{
partial class Georefimage : Form
{
enum PROCESSING_MODE
{
TIME_OFFSET,
CAM_MSG
}
public class PictureInformation : SingleLocation
{
string path;
public string Path
{
get { return path; }
set { path = value; }
}
DateTime shotTimeReportedByCamera;
public DateTime ShotTimeReportedByCamera
{
get { return shotTimeReportedByCamera; }
set { shotTimeReportedByCamera = value; }
}
int width;
public int Width
{
get { return width; }
set { width = value; }
}
int height;
public int Height
{
get { return height; }
set { height = value; }
}
public PictureInformation()
{
width = 3200;
height = 2400;
}
}
public class SingleLocation
{
DateTime time;
public DateTime Time
{
get { return time; }
set { time = value; }
}
double lat;
public double Lat
{
get { return lat; }
set { lat = value; }
}
double lon;
public double Lon
{
get { return lon; }
set { lon = value; }
}
double altAMSL;
public double AltAMSL
{
get { return altAMSL; }
set { altAMSL = value; }
}
double relAlt;
public double RelAlt
{
get { return relAlt; }
set { relAlt = value; }
}
float roll;
public float Roll
{
get { return roll; }
set { roll = value; }
}
float pitch;
public float Pitch
{
get { return pitch; }
set { pitch = value; }
}
float yaw;
public float Yaw
{
get { return yaw; }
set { yaw = value; }
}
public double getAltitude(bool AMSL)
{
return (AMSL ? AltAMSL : RelAlt);
}
}
public class VehicleLocation : SingleLocation
{
}
private const string PHOTO_FILES_FILTER = "*.jpg;*.tif";
private const int JXL_ID_OFFSET = 10;
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// CONSTS
const float rad2deg = (float)(180 / Math.PI);
const float deg2rad = (float)(1.0 / rad2deg);
// GPS Log positions
//Status,Time,NSats,HDop,Lat,Lng,RelAlt,Alt,Spd,GCrs
//GPS, 3, 122732, 10, 0.00, -35.3628880, 149.1621961, 808.90, 810.30, 23.30, 94.04
//GPS, 3, 23524837, 1790, 10, 0.00, -35.3629379, 149.165085, 2.09, 585.41, 0.00, 129.86, 0, 4001
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
int gpsweekpos = 3, timepos = 2, latpos = 6, lngpos = 7, altpos = 8, altAMSLpos = 9;
// ATT Msg Positions
// ATT, 199361, 0.00, -0.40, 0.00, -3.01, 103.03, 103.03
int pitchATT = 5, rollATT = 3, yawATT = 7;
// CAM Log positions
//CAM, 36028400, 1790, 37.4155135, -3.8520916, 69.93, -3.61, -3.82, 62.93
int timeCAMpos = 1, weekCAMPos = 2, latCAMpos = 3, lngCAMpos = 4, altCAMpos = 5, pitchCAMATT = 6, rollCAMATT = 7, yawCAMATT = 8;
#region GraphicalStuff
#endregion
// Key = path of file, Value = object with picture information
Dictionary<string, PictureInformation> picturesInfo;
// Key = time in milliseconds, Value = object with location info and attitude
Dictionary<long, VehicleLocation> vehicleLocations;
bool useAMSLAlt;
int millisShutterLag = 0;
Hashtable filedatecache = new Hashtable();
private CheckBox chk_cammsg;
private TextBox txt_basealt;
private Label label28;
List<int> JXL_StationIDs = new List<int>();
internal Georefimage() {
InitializeComponent();
CHECK_AMSLAlt_Use.Checked = true;
PANEL_TIME_OFFSET.Enabled = false;
useAMSLAlt = CHECK_AMSLAlt_Use.Checked;
JXL_StationIDs = new List<int>();
selectedProcessingMode = PROCESSING_MODE.CAM_MSG;
// Graphic init
// GPS
NUM_GPS_Week.Value = gpsweekpos;
NUM_time.Value = timepos;
NUM_latpos.Value = latpos;
NUM_lngpos.Value = lngpos;
NUM_altpos.Value = altpos;
NUM_GPS_AMSL_Alt.Value = altAMSLpos;
// ATT
NUM_ATT_Heading.Value = yawATT;
NUM_ATT_Pitch.Value = pitchATT;
NUM_ATT_Roll.Value = rollATT;
// CAM
NUM_CAM_Time.Value = timeCAMpos;
NUM_CAM_Week.Value = weekCAMPos;
NUM_CAM_Lat.Value = latCAMpos;
NUM_CAM_Lon.Value = lngCAMpos;
NUM_CAM_Alt.Value = altCAMpos;
NUM_CAM_Heading.Value = yawCAMATT;
NUM_CAM_Roll.Value = rollCAMATT;
NUM_CAM_Pitch.Value = pitchCAMATT;
MissionPlanner.Utilities.Tracking.AddPage(this.GetType().ToString(), this.Text);
}
DateTime getPhotoTime(string fn)
{
DateTime dtaken = DateTime.MinValue;
if (filedatecache.ContainsKey(fn))
{
return (DateTime)filedatecache[fn];
}
try
{
Metadata lcMetadata = null;
try
{
FileInfo lcImgFile = new FileInfo(fn);
// Loading all meta data
if (fn.ToLower().EndsWith(".jpg"))
{
lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile);
}
else if (fn.ToLower().EndsWith(".tif"))
{
lcMetadata = TiffMetadataReader.ReadMetadata(lcImgFile);
}
}
catch (JpegProcessingException e)
{
log.InfoFormat(e.Message);
return dtaken;
}
catch (TiffProcessingException e)
{
log.InfoFormat(e.Message);
return dtaken;
}
foreach (AbstractDirectory lcDirectory in lcMetadata)
{
if (lcDirectory.ContainsTag(0x9003))
{
dtaken = lcDirectory.GetDate(0x9003);
log.InfoFormat("does " + lcDirectory.GetTagName(0x9003) + " " + dtaken);
filedatecache[fn] = dtaken;
break;
}
if (lcDirectory.ContainsTag(0x9004))
{
dtaken = lcDirectory.GetDate(0x9004);
log.InfoFormat("does " + lcDirectory.GetTagName(0x9004) + " " + dtaken);
filedatecache[fn] = dtaken;
break;
}
}
////// old method, works, just slow
/*
Image myImage = Image.FromFile(fn);
PropertyItem propItem = myImage.GetPropertyItem(36867); // 36867 // 306
//Convert date taken metadata to a DateTime object
string sdate = Encoding.UTF8.GetString(propItem.Value).Trim();
string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" ")));
string firsthalf = sdate.Substring(0, 10);
firsthalf = firsthalf.Replace(":", "-");
sdate = firsthalf + secondhalf;
dtaken = DateTime.Parse(sdate);
myImage.Dispose();
*/
}
catch { }
return dtaken;
}
// Return List with all GPS Messages splitted in string arrays
Dictionary<long, VehicleLocation> readGPSMsgInLog(string fn)
{
Dictionary<long, VehicleLocation> vehiclePositionList = new Dictionary<long,VehicleLocation>();
// Telemetry Log
if (fn.ToLower().EndsWith("tlog"))
{
using (MAVLinkInterface mine = new MAVLinkInterface())
{
mine.logplaybackfile = new BinaryReader(File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.Read));
mine.logreadmode = true;
mine.MAV.packets.Initialize(); // clear
CurrentState cs = new CurrentState();
while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
{
byte[] packet = mine.readPacket();
cs.datetime = mine.lastlogread;
cs.UpdateCurrentSettings(null, true, mine);
VehicleLocation location = new VehicleLocation();
location.Time = cs.datetime;
location.Lat = cs.lat;
location.Lon = cs.lng;
location.RelAlt = cs.alt;
location.AltAMSL = cs.altasl;
location.Roll = cs.roll;
location.Pitch = cs.pitch;
location.Yaw = cs.yaw;
vehiclePositionList[ToMilliseconds(location.Time)] = location;
// 4 5 7
Console.Write((mine.logplaybackfile.BaseStream.Position * 100 / mine.logplaybackfile.BaseStream.Length) + " \r");
}
mine.logplaybackfile.Close();
}
}
// DataFlash Log
else
{
// convert bin to log
if (fn.ToLower().EndsWith("bin"))
{
string tempfile = Path.GetTempFileName();
Log.BinaryLog.ConvertBin(fn, tempfile);
fn = tempfile;
}
StreamReader sr = new StreamReader(fn);
// Will hold the last seen Attitude information in order to incorporate them into the GPS Info
float currentYaw = 0f;
float currentRoll = 0f;
float currentPitch = 0f;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
// Look for GPS Messages. However GPS Messages do not have Roll, Pitch and Yaw
// So we have to look for one ATT message after having read a GPS one
if (line.ToLower().StartsWith("gps"))
{
VehicleLocation location = new VehicleLocation();
string[] gpsLineValues = line.Split(new char[] { ',', ':' });
try
{
location.Time = GetTimeFromGps(int.Parse(getValueFromStringArray(gpsLineValues, gpsweekpos), CultureInfo.InvariantCulture), int.Parse(getValueFromStringArray(gpsLineValues, timepos), CultureInfo.InvariantCulture));
location.Lat = double.Parse(getValueFromStringArray(gpsLineValues, latpos), CultureInfo.InvariantCulture);
location.Lon = double.Parse(getValueFromStringArray(gpsLineValues, lngpos), CultureInfo.InvariantCulture);
location.RelAlt = double.Parse(getValueFromStringArray(gpsLineValues, altpos), CultureInfo.InvariantCulture);
location.AltAMSL = double.Parse(getValueFromStringArray(gpsLineValues, altAMSLpos), CultureInfo.InvariantCulture);
location.Roll = currentRoll;
location.Pitch = currentPitch;
location.Yaw = currentYaw;
long millis = ToMilliseconds(location.Time);
//System.Diagnostics.Debug.WriteLine("GPS MSG - UTCMillis = " + millis + " GPS Week = " + getValueFromStringArray(gpsLineValues, gpsweekpos) + " TimeMS = " + getValueFromStringArray(gpsLineValues, timepos));
if (!vehiclePositionList.ContainsKey(millis))
vehiclePositionList[millis] = location;
}
catch { Console.WriteLine("Bad GPS Line"); }
}
else if (line.ToLower().StartsWith("att"))
{
string[] attLineValues = line.Split(new char[] { ',', ':' });
currentRoll = float.Parse(getValueFromStringArray(attLineValues, rollATT), CultureInfo.InvariantCulture);
currentPitch = float.Parse(getValueFromStringArray(attLineValues, pitchATT), CultureInfo.InvariantCulture);
currentYaw = float.Parse(getValueFromStringArray(attLineValues, yawATT), CultureInfo.InvariantCulture);
}
}
sr.Close();
}
return vehiclePositionList;
}
// Return List with all CAMs messages splitted in string arrays
Dictionary<long, VehicleLocation> readCAMMsgInLog(string fn)
{
Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();
if (fn.ToLower().EndsWith("tlog"))
return null;
// convert bin to log
if (fn.ToLower().EndsWith("bin"))
{
string tempfile = Path.GetTempFileName();
Log.BinaryLog.ConvertBin(fn, tempfile);
fn = tempfile;
}
using (StreamReader sr = new StreamReader(fn))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.ToLower().StartsWith("cam"))
{
string[] currentCAM = line.Split(new char[] { ',', ':' });
VehicleLocation p = new VehicleLocation();
p.Time = GetTimeFromGps(int.Parse(getValueFromStringArray(currentCAM, weekCAMPos), CultureInfo.InvariantCulture), int.Parse(getValueFromStringArray(currentCAM, timeCAMpos), CultureInfo.InvariantCulture));
p.Lat = double.Parse(getValueFromStringArray(currentCAM, latCAMpos), CultureInfo.InvariantCulture);
p.Lon = double.Parse(getValueFromStringArray(currentCAM, lngCAMpos), CultureInfo.InvariantCulture);
p.AltAMSL = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);
p.RelAlt = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);
p.Pitch = float.Parse(getValueFromStringArray(currentCAM, pitchCAMATT), CultureInfo.InvariantCulture);
p.Roll = float.Parse(getValueFromStringArray(currentCAM, rollCAMATT), CultureInfo.InvariantCulture);
p.Yaw = float.Parse(getValueFromStringArray(currentCAM, yawCAMATT), CultureInfo.InvariantCulture);
list[ToMilliseconds(p.Time)] = p;
}
}
}
return list;
}
// Return List with all CAMs messages splitted in string arrays
List<string[]> readCAMMsgInLogString(string fn)
{
List<string[]> list = new List<string[]>();
if (fn.ToLower().EndsWith("tlog"))
return null;
// convert bin to log
if (fn.ToLower().EndsWith("bin"))
{
string tempfile = Path.GetTempFileName();
Log.BinaryLog.ConvertBin(fn, tempfile);
fn = tempfile;
}
using (StreamReader sr = new StreamReader(fn))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.ToLower().StartsWith("cam"))
{
string[] vals = line.Split(new char[] { ',', ':' });
list.Add(vals);
}
}
}
return list;
}
#region HelperMethods
// return a value in an array securely
public string getValueFromStringArray(string[] array, int position)
{
string sResult = "-1";
if (position < array.Length)
sResult = array[position];
return sResult;
}
public DateTime FromUTCTimeMilliseconds(long milliseconds)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(milliseconds);
}
public DateTime GetTimeFromGps(int weeknumber, int milliseconds)
{
int LEAP_SECONDS = 16;
DateTime datum = new DateTime(1980, 1, 6, 0, 0, 0, DateTimeKind.Utc);
DateTime week = datum.AddDays(weeknumber * 7);
DateTime time = week.AddMilliseconds(milliseconds);
return time.AddSeconds(-LEAP_SECONDS);
}
public long ToMilliseconds(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date - epoch).TotalMilliseconds);
}
#endregion
private double EstimateOffset(string logFile, string dirWithImages)
{
if (vehicleLocations == null || vehicleLocations.Count <= 0)
{
if (chk_cammsg.Checked)
{
vehicleLocations = readCAMMsgInLog(logFile);
}
else
{
vehicleLocations = readGPSMsgInLog(logFile);
}
}
if (vehicleLocations == null || vehicleLocations.Count <= 0)
return -1;
List<string> filelist = new List<string>();
string[] exts = PHOTO_FILES_FILTER.Split(';');
foreach (var ext in exts)
{
filelist.AddRange(Directory.GetFiles(dirWithImages, ext));
}
string[] files = filelist.ToArray();
if (files == null || files.Length == 0)
return -1;
Array.Sort(files, Comparer.DefaultInvariant);
double ans = 0;
TXT_outputlog.Clear();
for (int a = 0; a < 4; a++)
{
// First Photo time
string firstPhoto = files[a];
DateTime photoTime = getPhotoTime(firstPhoto);
TXT_outputlog.AppendText((a+1) + " Picture " + Path.GetFileNameWithoutExtension(firstPhoto) + " with DateTime: " + photoTime.ToString("yyyy:MM:dd HH:mm:ss") + "\n");
// First GPS Message in Log time
List<long> times = new List<long>(vehicleLocations.Keys);
times.Sort();
long firstTimeInGPSMsg = times[a];
DateTime logTime = FromUTCTimeMilliseconds(firstTimeInGPSMsg);
TXT_outputlog.AppendText((a+1) + " GPS Log Msg: " + logTime.ToString("yyyy:MM:dd HH:mm:ss") + "\n");
TXT_outputlog.AppendText((a + 1) + " Est: " + (double)(photoTime - logTime).TotalSeconds + "\n");
if (ans == 0)
ans = (double)(photoTime - logTime).TotalSeconds;
}
return ans;
}
private void CreateReportFiles(Dictionary<string, PictureInformation> listPhotosWithInfo, string dirWithImages, float offset)
{
// Write report files
Document kmlroot = new Document();
Folder kml = new Folder("Pins");
Folder overlayfolder = new Folder("Overlay");
// add root folder to document
kmlroot.AddFeature(kml);
kmlroot.AddFeature(overlayfolder);
// Clear Stations IDs
JXL_StationIDs.Clear();
using (StreamWriter swlogloccsv = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "loglocation.csv"))
using (StreamWriter swlockml = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.kml"))
using (StreamWriter swloctxt = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.txt"))
using (StreamWriter swloctel = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.tel"))
using (XmlTextWriter swloctrim = new XmlTextWriter(dirWithImages + Path.DirectorySeparatorChar + "location.jxl", Encoding.ASCII))
{
swloctrim.Formatting = Formatting.Indented;
swloctrim.WriteStartDocument(false);
swloctrim.WriteStartElement("JOBFile");
swloctrim.WriteAttributeString("jobName", "MPGeoRef");
swloctrim.WriteAttributeString("product", "Gatewing");
swloctrim.WriteAttributeString("productVersion", "1.0");
swloctrim.WriteAttributeString("version", "5.6");
// enviro
swloctrim.WriteStartElement("Environment");
swloctrim.WriteStartElement("CoordinateSystem");
swloctrim.WriteElementString("SystemName", "Default");
swloctrim.WriteElementString("ZoneName", "Default");
swloctrim.WriteElementString("DatumName", "WGS 1984");
swloctrim.WriteStartElement("Ellipsoid");
swloctrim.WriteElementString("EarthRadius", "6378137");
swloctrim.WriteElementString("Flattening", "0.00335281067183");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("Projection");
swloctrim.WriteElementString("Type", "NoProjection");
swloctrim.WriteElementString("Scale", "1");
swloctrim.WriteElementString("GridOrientation", "IncreasingNorthEast");
swloctrim.WriteElementString("SouthAzimuth", "false");
swloctrim.WriteElementString("ApplySeaLevelCorrection", "true");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("LocalSite");
swloctrim.WriteElementString("Type", "Grid");
swloctrim.WriteElementString("ProjectLocationLatitude", "");
swloctrim.WriteElementString("ProjectLocationLongitude", "");
swloctrim.WriteElementString("ProjectLocationHeight", "");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("Datum");
swloctrim.WriteElementString("Type", "ThreeParameter");
swloctrim.WriteElementString("GridName", "WGS 1984");
swloctrim.WriteElementString("Direction", "WGS84ToLocal");
swloctrim.WriteElementString("EarthRadius", "6378137");
swloctrim.WriteElementString("Flattening", "0.00335281067183");
swloctrim.WriteElementString("TranslationX", "0");
swloctrim.WriteElementString("TranslationY", "0");
swloctrim.WriteElementString("TranslationZ", "0");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("HorizontalAdjustment");
swloctrim.WriteElementString("Type", "NoAdjustment");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("VerticalAdjustment");
swloctrim.WriteElementString("Type", "NoAdjustment");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("CombinedScaleFactor");
swloctrim.WriteStartElement("Location");
swloctrim.WriteElementString("Latitude", "");
swloctrim.WriteElementString("Longitude", "");
swloctrim.WriteElementString("Height", "");
swloctrim.WriteEndElement();
swloctrim.WriteElementString("Scale", "");
swloctrim.WriteEndElement();
swloctrim.WriteEndElement();
swloctrim.WriteEndElement();
// fieldbook
swloctrim.WriteStartElement("FieldBook");
swloctrim.WriteRaw(@" <CameraDesignRecord ID='00000001'>
<Type>GoPro </Type>
<HeightPixels>2400</HeightPixels>
<WidthPixels>3200</WidthPixels>
<PixelSize>0.0000022</PixelSize>
<LensModel>Rectilinear</LensModel>
<NominalFocalLength>0.002</NominalFocalLength>
</CameraDesignRecord>
<CameraRecord2 ID='00000002'>
<CameraDesignID>00000001</CameraDesignID>
<CameraPosition>01</CameraPosition>
<Optics>
<IdealAngularMagnification>1.0</IdealAngularMagnification>
<AngleSymmetricDistortion>
<Order3>-0.35</Order3>
<Order5>0.15</Order5>
<Order7>-0.033</Order7>
<Order9> 0</Order9>
</AngleSymmetricDistortion>
<AngleDecenteringDistortion>
<Column>0</Column>
<Row>0</Row>
</AngleDecenteringDistortion>
</Optics>
<Geometry>
<PerspectiveCenterPixels>
<PrincipalPointColumn>-1615.5</PrincipalPointColumn>
<PrincipalPointRow>-1187.5</PrincipalPointRow>
<PrincipalDistance>-2102</PrincipalDistance>
</PerspectiveCenterPixels>
<VectorOffset>
<X>0</X>
<Y>0</Y>
<Z>0</Z>
</VectorOffset>
<BiVectorAngle>
<XX>0</XX>
<YY>0</YY>
<ZZ>-1.5707963268</ZZ>
</BiVectorAngle>
</Geometry>
</CameraRecord2>");
// 2mm fl
// res 2400 * 3200 = 7,680,000
// sensor size = 1/2.5" - 5.70 × 4.28 mm
// 2.2 μm
// fl in pixels = fl in mm * res / sensor size
swloctrim.WriteStartElement("PhotoInstrumentRecord");
swloctrim.WriteAttributeString("ID", "0000000E");
swloctrim.WriteElementString("Type", "Aerial");
swloctrim.WriteElementString("Model", "X100");
swloctrim.WriteElementString("Serial", "000-000");
swloctrim.WriteElementString("FirmwareVersion", "v0.0");
swloctrim.WriteElementString("UserDefinedName", "Prototype");
swloctrim.WriteEndElement();
swloctrim.WriteStartElement("AtmosphereRecord");
swloctrim.WriteAttributeString("ID", "0000000F");
swloctrim.WriteElementString("Pressure", "");
swloctrim.WriteElementString("Temperature", "");
swloctrim.WriteElementString("PPM", "");
swloctrim.WriteElementString("ApplyEarthCurvatureCorrection", "false");
swloctrim.WriteElementString("ApplyRefractionCorrection", "false");
swloctrim.WriteElementString("RefractionCoefficient", "0");
swloctrim.WriteElementString("PressureInputMethod", "ReadFromInstrument");
swloctrim.WriteEndElement();
swloctel.WriteLine("version=1");
swloctel.WriteLine("#seconds offset - " + offset);
swloctel.WriteLine("#longitude and latitude - in degrees");
swloctel.WriteLine("#name utc longitude latitude height");
swloctxt.WriteLine("#name latitude/Y longitude/X height/Z yaw pitch roll");
TXT_outputlog.AppendText("Start Processing\n");
// Dont know why but it was 10 in the past so let it be. Used to generate jxl file simulating x100 from trimble
int lastRecordN = JXL_ID_OFFSET;
// path
CoordinateCollection coords = new CoordinateCollection();
foreach (var item in vehicleLocations.Values)
{
coords.Add(new SharpKml.Base.Vector(item.Lat, item.Lon, item.AltAMSL));
}
var ls = new LineString() { Coordinates = coords, AltitudeMode = AltitudeMode.Absolute };
SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark() { Geometry = ls, Name = "path" };
kml.AddFeature(pm);
foreach (PictureInformation picInfo in listPhotosWithInfo.Values)
{
string filename = Path.GetFileName(picInfo.Path);
string filenameWithoutExt = Path.GetFileNameWithoutExtension(picInfo.Path);
SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
tstamp.When = picInfo.Time;
kml.AddFeature(
new Placemark()
{
Time = tstamp,
Visibility = true,
Name = filenameWithoutExt,
Geometry = new SharpKml.Dom.Point()
{
Coordinate = new Vector(picInfo.Lat, picInfo.Lon, picInfo.AltAMSL),
AltitudeMode = AltitudeMode.Absolute
},
Description = new Description()
{
Text = "<table><tr><td><img src=\"" + filename.ToLower() + "\" width=500 /></td></tr></table>"
},
StyleSelector = new Style()
{
Balloon = new BalloonStyle() { Text = "$[name]<br>$[description]" }
}
}
);
double lat = picInfo.Lat;
double lng = picInfo.Lon;
double alpha = picInfo.Yaw + (double)num_camerarotation.Value;;
RectangleF rect = getboundingbox(lat, lng, alpha, (double)num_hfov.Value, (double)num_vfov.Value);
Console.WriteLine(rect);
//http://en.wikipedia.org/wiki/World_file
/* using (StreamWriter swjpw = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".jgw"))
{
swjpw.WriteLine((rect.Height / 2448.0).ToString("0.00000000000000000"));
swjpw.WriteLine((0).ToString("0.00000000000000000")); //
swjpw.WriteLine((0).ToString("0.00000000000000000")); //
swjpw.WriteLine((rect.Width / -3264.0).ToString("0.00000000000000000")); // distance per pixel
swjpw.WriteLine((rect.Left).ToString("0.00000000000000000"));
swjpw.WriteLine((rect.Top).ToString("0.00000000000000000"));
swjpw.Close();
}*/
overlayfolder.AddFeature(
new GroundOverlay()
{
Name = filenameWithoutExt,
Visibility = false,
Time = tstamp,
AltitudeMode = AltitudeMode.ClampToGround,
Bounds = new LatLonBox()
{
Rotation = -alpha % 360,
North = rect.Bottom,
East = rect.Right,
West = rect.Left,
South = rect.Top,
},
Icon = new SharpKml.Dom.Icon()
{
Href = new Uri(filename.ToLower(), UriKind.Relative),
},
}
);
swloctxt.WriteLine(filename + " " + picInfo.Lat + " " + picInfo.Lon + " " + picInfo.getAltitude(useAMSLAlt) + " " + picInfo.Yaw + " " + picInfo.Pitch + " " + picInfo.Roll);
swloctel.WriteLine(filename + "\t" + picInfo.Time.ToString("yyyy:MM:dd HH:mm:ss") + "\t" + picInfo.Lon + "\t" + picInfo.Lat + "\t" + picInfo.getAltitude(useAMSLAlt));
swloctel.Flush();
swloctxt.Flush();
lastRecordN = GenPhotoStationRecord(swloctrim, picInfo.Path, picInfo.Lat, picInfo.Lon, picInfo.getAltitude(useAMSLAlt), 0, 0, picInfo.Yaw, picInfo.Width, picInfo.Height, lastRecordN);
log.InfoFormat(filename + " " + picInfo.Lon + " " + picInfo.Lat + " " + picInfo.getAltitude(useAMSLAlt) + " ");
}
Serializer serializer = new Serializer();
serializer.Serialize(kmlroot);
swlockml.Write(serializer.Xml);
Utilities.httpserver.georefkml = serializer.Xml;
Utilities.httpserver.georefimagepath = dirWithImages + Path.DirectorySeparatorChar;
writeGPX(dirWithImages + Path.DirectorySeparatorChar + "location.gpx", listPhotosWithInfo);
// flightmission
GenFlightMission(swloctrim, lastRecordN);
swloctrim.WriteEndElement(); // fieldbook
swloctrim.WriteEndElement(); // job
swloctrim.WriteEndDocument();
TXT_outputlog.AppendText("Done \n\n");
}
}
private VehicleLocation LookForLocation(DateTime t, Dictionary<long, VehicleLocation> listLocations, int offsettime = 2000)
{
long time = ToMilliseconds(t);
// Time at which the GPS position is actually search and found
long actualTime = time;
int millisSTEP = 1;
// 2 seconds (2000 ms) in the log as absolute maximum
int maxIteration = offsettime;
bool found = false;
int iteration = 0;
VehicleLocation location = null;
while (!found && iteration < maxIteration)
{
found = listLocations.ContainsKey(actualTime);
if (found)
{
location = listLocations[actualTime];
}
else
{
actualTime += millisSTEP;
iteration++;
}
}
/*if (location == null)
TXT_outputlog.AppendText("Time not found in log: " + time + "\n");
else
TXT_outputlog.AppendText("GPS position found " + (actualTime - time) + " ms away\n");*/
return location;
}
public Dictionary<string, PictureInformation> doworkGPSOFFSET(string logFile, string dirWithImages, float offset)
{
// Lets start over
Dictionary<string, PictureInformation> picturesInformationTemp = new Dictionary<string, PictureInformation>();
// Read Vehicle Locations from log. GPS Messages. Will have to do it anyway
if (vehicleLocations == null || vehicleLocations.Count <= 0)
{
if (chk_cammsg.Checked)
{
TXT_outputlog.AppendText("Reading log for CAM Messages\n");
vehicleLocations = readCAMMsgInLog(logFile);
}
else
{
TXT_outputlog.AppendText("Reading log for GPS-ATT Messages\n");
vehicleLocations = readGPSMsgInLog(logFile);
}
}
if (vehicleLocations == null)
{
TXT_outputlog.AppendText("Log file problem. Aborting....\n");
return null;
}
TXT_outputlog.AppendText("Read images\n");
List<string> filelist = new List<string>();
string[] exts = PHOTO_FILES_FILTER.Split(';');
foreach (var ext in exts)
{
filelist.AddRange(Directory.GetFiles(dirWithImages, ext));
}
string[] files = filelist.ToArray();
TXT_outputlog.AppendText("Images read : " + files.Length + "\n");
// Check that we have at least one picture
if (files.Length <= 0)
{
TXT_outputlog.AppendText("Not enought files found. Aborting..... \n");
return null;
}
Array.Sort(files, Comparer.DefaultInvariant);
// Each file corresponds to one CAM message
// We assume that picture names are in ascending order in time
for (int i = 0; i < files.Length; i++)
{
string filename = files[i];
PictureInformation p = new PictureInformation();
// Fill shot time in Picture
p.ShotTimeReportedByCamera = getPhotoTime(filename);
// Lookfor corresponding Location in vehicleLocationList
DateTime correctedTime = p.ShotTimeReportedByCamera.AddSeconds(-offset);
VehicleLocation shotLocation = LookForLocation(correctedTime, vehicleLocations, 5000);
if (shotLocation == null)
{
TXT_outputlog.AppendText("Photo " + Path.GetFileNameWithoutExtension(filename) + " NOT PROCESSED. No GPS match in the log file. Please take care\n");