-
Notifications
You must be signed in to change notification settings - Fork 2
/
GeoTiff.cs
570 lines (495 loc) · 22.3 KB
/
GeoTiff.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
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using BitMiracle.LibTiff.Classic;
using GeoTiffCOG.Struture;
namespace GeoTiffCOG
{
public class GeoTiff
{
BitMiracle.LibTiff.Classic.Tiff _tiff;
string _tiffPath;
TraceTiffErrorHandler _traceLogHandler = new TraceTiffErrorHandler();
Dictionary<int, byte[]> tilesCache;
public FileMetadata metadata { get; private set; }
internal Tiff TiffFile
{
get { return _tiff; }
}
public string FilePath
{
get { return _tiffPath; }
}
public GeoTiff(Uri urlCOG, string directoryCache)
{
Tiff.SetErrorHandler(_traceLogHandler);
_tiff = Tiff.ClientOpen("tiff", "r", null, new TiffSteamCustom(urlCOG.ToString(), directoryCache));
metadata = this.ParseMetaData(new DEMFileDefinition());
}
public GeoTiff(string tiffPath)
{
Tiff.SetErrorHandler(_traceLogHandler);
if (!File.Exists(tiffPath))
throw new Exception($"File {tiffPath} does not exists !");
_tiffPath = tiffPath;
_tiff = Tiff.Open(tiffPath, "r");
if (_tiff == null)
throw new Exception($"File {tiffPath} cannot be opened !");
metadata = this.ParseMetaData(new DEMFileDefinition());
}
#region Tile info
int tileWidth = 0;
internal int TileWidth
{
get
{
if (tileWidth == 0)
{
tileWidth = TiffFile.GetField(TiffTag.TILEWIDTH)[0].ToInt();
}
return tileWidth;
}
}
int tileHeight = 0;
internal int TileHeight
{
get
{
if (tileHeight == 0)
{
tileHeight = TiffFile.GetField(TiffTag.TILELENGTH)[0].ToInt();
}
return tileHeight;
}
}
int tileSize = 0;
internal int TileSize
{
get
{
if (tileSize == 0)
{
tileSize = TiffFile.TileSize();
}
return tileSize;
}
}
bool isTiledSet = false;
bool isTiled;
internal bool IsTiled
{
get
{
if (isTiledSet == false)
{
isTiled = TiffFile.IsTiled();
isTiledSet = true;
}
return isTiled;
}
}
#endregion
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_tiff?.Dispose();
if (tilesCache != null)
{
tilesCache.Clear();
tilesCache = null;
}
}
}
~GeoTiff()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public float GetElevationAtLatLon(double latitude, double longitude)
{
var bbox = new double[] { metadata.DataStartLon, metadata.DataStartLat, metadata.DataEndLon, metadata.DataEndLat };
var pixelWidth = metadata.Width;
var pixelHeight = metadata.Height;
var bboxWidth = bbox[2] - bbox[0];
var bboxHeight = bbox[3] - bbox[1];
var widthPct = (longitude - bbox[0]) / bboxWidth;
var heightPct = (latitude - bbox[1]) / bboxHeight;
var x = (int)(Math.Floor(pixelWidth * widthPct));
var y = (int)(Math.Floor(pixelHeight * (1 - heightPct)));
return GetElevationAtPoint(x, y);
}
public float GetElevationAtPoint(int x, int y)
{
float heightValue = 0;
try
{
if (this.IsTiled)
{
// TODO store in metadata
int tileWidth = this.TileWidth;
int tileHeight = this.TileHeight;
int tileSize = this.TileSize;
byte[] buffer;
var tileX = (x / tileWidth) * tileWidth;
var tileY = (y / tileHeight) * tileHeight;
if (tilesCache == null) tilesCache = new Dictionary<int, byte[]>();
var tileKey = (x / tileWidth) + (y / tileHeight) * (metadata.Width / tileWidth + 1);
if (!tilesCache.TryGetValue(tileKey, out buffer))
{
buffer = new byte[tileSize];
TiffFile.ReadTile(buffer, 0, tileX, tileY, 0, 0);
tilesCache.Add(tileKey, buffer);
}
var offset = x - tileX + (y - tileY) * tileHeight;
heightValue = GetElevationAtPoint(offset, buffer);
}
else
{
// metadata.BitsPerSample
// When 16 we have 2 bytes per sample
// When 32 we have 4 bytes per sample
int bytesPerSample = metadata.BitsPerSample / 8;
byte[] byteScanline = new byte[metadata.ScanlineSize];
TiffFile.ReadScanline(byteScanline, y);
heightValue = GetElevationAtPoint(x, byteScanline);
}
}
catch (Exception e)
{
throw new Exception($"Error in ParseGeoDataAtPoint: {e.Message}");
}
return heightValue;
}
public float GetElevationAtPoint(int offset, byte[] buffer)
{
float heightValue = 0;
try
{
switch (metadata.SampleFormat)
{
case RasterSampleFormat.FLOATING_POINT:
heightValue = BitConverter.ToSingle(buffer, offset * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.INTEGER:
heightValue = BitConverter.ToInt16(buffer, offset * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.UNSIGNED_INTEGER:
heightValue = BitConverter.ToUInt16(buffer, offset * metadata.BitsPerSample / 8);
break;
default:
throw new Exception("Sample format unsupported.");
}
if (heightValue > 32768)
{
heightValue = metadata.NoDataValueFloat;
}
}
catch (Exception e)
{
throw new Exception($"Error in ParseGeoDataAtPoint: {e.Message}");
}
return heightValue;
}
public float GetElevationAtPointRef(int offset, ref byte[] buffer)
{
float heightValue = 0;
try
{
switch (metadata.SampleFormat)
{
case RasterSampleFormat.FLOATING_POINT:
heightValue = BitConverter.ToSingle(buffer, offset * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.INTEGER:
heightValue = BitConverter.ToInt16(buffer, offset * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.UNSIGNED_INTEGER:
heightValue = BitConverter.ToUInt16(buffer, offset * metadata.BitsPerSample / 8);
break;
default:
throw new Exception("Sample format unsupported.");
}
if (heightValue > 32768)
{
heightValue = metadata.NoDataValueFloat;
}
}
catch (Exception e)
{
throw new Exception($"Error in ParseGeoDataAtPoint: {e.Message}");
}
return heightValue;
}
private FileMetadata ParseMetaData(DEMFileDefinition format)
{
FileMetadata _metadata = new FileMetadata(FilePath, format);
///
_metadata.Height = TiffFile.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
_metadata.Width = TiffFile.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
///
FieldValue[] modelPixelScaleTag = TiffFile.GetField(TiffTag.GEOTIFF_MODELPIXELSCALETAG);
FieldValue[] modelTiepointTag = TiffFile.GetField(TiffTag.GEOTIFF_MODELTIEPOINTTAG);
byte[] modelPixelScale = modelPixelScaleTag[1].GetBytes();
double pixelSizeX = BitConverter.ToDouble(modelPixelScale, 0);
double pixelSizeY = BitConverter.ToDouble(modelPixelScale, 8) * -1;
_metadata.pixelSizeX = pixelSizeX;
_metadata.pixelSizeY = pixelSizeY;
_metadata.PixelScaleX = BitConverter.ToDouble(modelPixelScale, 0);
_metadata.PixelScaleY = BitConverter.ToDouble(modelPixelScale, 8);
// Ignores first set of model points (3 bytes) and assumes they are 0's...
byte[] modelTransformation = modelTiepointTag[1].GetBytes();
_metadata.DataStartLon = BitConverter.ToDouble(modelTransformation, 24);
_metadata.DataStartLat = BitConverter.ToDouble(modelTransformation, 32);
_metadata.DataEndLon = _metadata.DataStartLon + _metadata.Width * pixelSizeX;
_metadata.DataEndLat = _metadata.DataStartLat + _metadata.Height * pixelSizeY;
if (_metadata.DataStartLon > _metadata.DataEndLon)
{
double temp = _metadata.DataStartLon;
_metadata.DataStartLon = _metadata.DataEndLon;
_metadata.DataEndLon = temp;
}
if (_metadata.DataStartLat > _metadata.DataEndLat)
{
double temp = _metadata.DataStartLat;
_metadata.DataStartLat = _metadata.DataEndLat;
_metadata.DataEndLat = temp;
}
if (format.Registration == DEMFileRegistrationMode.Grid)
{
_metadata.PhysicalStartLat = _metadata.DataStartLat;
_metadata.PhysicalStartLon = _metadata.DataStartLon;
_metadata.PhysicalEndLat = _metadata.DataEndLat;
_metadata.PhysicalEndLon = _metadata.DataEndLon;
_metadata.DataStartLat = Math.Round(_metadata.DataStartLat + (_metadata.PixelScaleY / 2.0), 10);
_metadata.DataStartLon = Math.Round(_metadata.DataStartLon + (_metadata.PixelScaleX / 2.0), 10);
_metadata.DataEndLat = Math.Round(_metadata.DataEndLat - (_metadata.PixelScaleY / 2.0), 10);
_metadata.DataEndLon = Math.Round(_metadata.DataEndLon - (_metadata.PixelScaleX / 2.0), 10);
}
else
{
_metadata.PhysicalStartLat = _metadata.DataStartLat;
_metadata.PhysicalStartLon = _metadata.DataStartLon;
_metadata.PhysicalEndLat = _metadata.DataEndLat;
_metadata.PhysicalEndLon = _metadata.DataEndLon;
}
var scanline = new byte[TiffFile.ScanlineSize()];
_metadata.ScanlineSize = TiffFile.ScanlineSize();
// Grab some raster _metadata
_metadata.BitsPerSample = TiffFile.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
var sampleFormat = TiffFile.GetField(TiffTag.SAMPLEFORMAT);
// Add other information about the data
_metadata.SampleFormat = sampleFormat[0].Value.ToString();
// TODO: Read this from tiff _metadata or determine after parsing
_metadata.NoDataValue = "-10000";
_metadata.WorldUnits = "meter";
return _metadata;
}
public HeightMap GetHeightMapInBBox(BoundingBox bbox, float noDataValue = 0)
{
int yStart = 0;
int yEnd = 0;
int xStart = 0;
int xEnd = 0;
if (metadata.FileFormat.Registration == DEMFileRegistrationMode.Grid)
{
yStart = (int)Math.Floor((bbox.yMax - metadata.PhysicalEndLat) / metadata.pixelSizeY);
yEnd = (int)Math.Ceiling((bbox.yMin - metadata.PhysicalEndLat) / metadata.pixelSizeY);
xStart = (int)Math.Floor((bbox.xMin - metadata.PhysicalStartLon) / metadata.pixelSizeX);
xEnd = (int)Math.Ceiling((bbox.xMax - metadata.PhysicalStartLon) / metadata.pixelSizeX);
}
else
{
yStart = (int)Math.Floor((bbox.yMax - metadata.DataEndLat) / metadata.pixelSizeY);
yEnd = (int)Math.Ceiling((bbox.yMin - metadata.DataEndLat) / metadata.pixelSizeY);
xStart = (int)Math.Floor((bbox.xMin - metadata.DataStartLon) / metadata.pixelSizeX);
xEnd = (int)Math.Ceiling((bbox.xMax - metadata.DataStartLon) / metadata.pixelSizeX);
}
// Tiled geotiffs like aster have overlapping 1px borders
int overlappingPixel = this.IsTiled ? 1 : 0;
xStart = Math.Max(0, xStart);
xEnd = Math.Min(metadata.Width - 1, xEnd) - overlappingPixel;
yStart = Math.Max(0, yStart);
yEnd = Math.Min(metadata.Height - 1, yEnd) - overlappingPixel;
HeightMap heightMap = new HeightMap(xEnd - xStart + 1, yEnd - yStart + 1);
heightMap.Count = heightMap.Width * heightMap.Height;
var coords = new List<GeoPoint>(heightMap.Count);
heightMap.BoundingBox = new BoundingBox(0, 0, 0, 0);
if (this.IsTiled)
{
// Tiled rasters are composed of multiple "sub" images
// TODO store in metadata
int tileWidth = this.TileWidth;
int tileHeight = this.TileHeight;
int tileSize = this.TileSize;
byte[] buffer;
for (int y = yStart; y <= yEnd; y++)
{
double latitude = metadata.DataEndLat + (metadata.pixelSizeY * y);
// bounding box
if (y == yStart)
{
heightMap.BoundingBox.yMax = latitude;
heightMap.BoundingBox.xMin = metadata.DataStartLon + (metadata.pixelSizeX * xStart);
heightMap.BoundingBox.xMax = metadata.DataStartLon + (metadata.pixelSizeX * xEnd);
}
if (y == yEnd)
{
heightMap.BoundingBox.yMin = latitude;
}
for (int x = xStart; x <= xEnd; x++)
{
double longitude = metadata.DataStartLon + (metadata.pixelSizeX * x);
var tileX = (x / tileWidth) * tileWidth;
var tileY = (y / tileHeight) * tileHeight;
if (tilesCache == null) tilesCache = new Dictionary<int, byte[]>();
var tileKey = (x / tileWidth) + (y / tileHeight) * (metadata.Width / tileWidth + 1);
if (!tilesCache.TryGetValue(tileKey, out buffer))
{
buffer = new byte[tileSize];
TiffFile.ReadTile(buffer, 0, tileX, tileY, 0, 0);
tilesCache.Add(tileKey, buffer);
}
var offset = x - tileX + (y - tileY) * tileHeight;
float heightValue = GetElevationAtPoint(offset, buffer);
if (heightValue <= 0)
{
heightMap.Minimum = Math.Min(heightMap.Minimum, heightValue);
heightMap.Maximum = Math.Max(heightMap.Maximum, heightValue);
}
else if (heightValue < 32768)
{
heightMap.Minimum = Math.Min(heightMap.Minimum, heightValue);
heightMap.Maximum = Math.Max(heightMap.Maximum, heightValue);
}
else
{
heightValue = (float)noDataValue;
}
coords.Add(new GeoPoint(latitude, longitude, heightValue));
}
}
}
else
{
// metadata.BitsPerSample
// When 16 we have 2 bytes per sample
// When 32 we have 4 bytes per sample
int bytesPerSample = metadata.BitsPerSample / 8;
byte[] byteScanline = new byte[metadata.ScanlineSize];
double endLat = metadata.DataEndLat + metadata.pixelSizeY / 2d;
double startLon = metadata.DataStartLon + metadata.pixelSizeX / 2d;
for (int y = yStart; y <= yEnd; y++)
{
TiffFile.ReadScanline(byteScanline, y);
// TODO: handle Cell registered DEMs: lat is 1/2 pixel off
double latitude = endLat + (metadata.pixelSizeY * y);
// bounding box
if (y == yStart)
{
heightMap.BoundingBox.yMax = latitude;
heightMap.BoundingBox.xMin = startLon + (metadata.pixelSizeX * xStart);
heightMap.BoundingBox.xMax = startLon + (metadata.pixelSizeX * xEnd);
}
else if (y == yEnd)
{
heightMap.BoundingBox.yMin = latitude;
}
for (int x = xStart; x <= xEnd; x++)
{
double longitude = startLon + (metadata.pixelSizeX * x);
float heightValue = 0;
switch (metadata.SampleFormat)
{
case RasterSampleFormat.FLOATING_POINT:
heightValue = BitConverter.ToSingle(byteScanline, x * bytesPerSample);
break;
case RasterSampleFormat.INTEGER:
heightValue = BitConverter.ToInt16(byteScanline, x * bytesPerSample);
break;
case RasterSampleFormat.UNSIGNED_INTEGER:
heightValue = BitConverter.ToUInt16(byteScanline, x * bytesPerSample);
break;
default:
throw new Exception("Sample format unsupported.");
}
if (heightValue <= 0)
{
heightMap.Minimum = Math.Min(heightMap.Minimum, heightValue);
heightMap.Maximum = Math.Max(heightMap.Maximum, heightValue);
}
else if (heightValue < 32768)
{
heightMap.Minimum = Math.Min(heightMap.Minimum, heightValue);
heightMap.Maximum = Math.Max(heightMap.Maximum, heightValue);
}
else
{
heightValue = (float)noDataValue;
}
coords.Add(new GeoPoint(latitude, longitude, heightValue));
}
}
}
heightMap.BoundingBox.zMin = heightMap.Minimum;
heightMap.BoundingBox.zMax = heightMap.Maximum;
Debug.Assert(heightMap.Width * heightMap.Height == coords.Count);
heightMap.Coordinates = coords;
return heightMap;
}
public HeightMap GetHeightMap()
{
if (this.isTiled)
throw new NotImplementedException("Whole height map with tile geoTiff is not implemented");
HeightMap heightMap = new HeightMap(metadata.Width, metadata.Height);
heightMap.Count = heightMap.Width * heightMap.Height;
var coords = new List<GeoPoint>(heightMap.Count);
// metadata.BitsPerSample
// When 16 we have 2 bytes per sample
// When 32 we have 4 bytes per sample
int bytesPerSample = metadata.BitsPerSample / 8;
byte[] byteScanline = new byte[metadata.ScanlineSize];
for (int y = 0; y < metadata.Height; y++)
{
TiffFile.ReadScanline(byteScanline, y);
double latitude = metadata.DataStartLat + (metadata.pixelSizeY * y);
for (int x = 0; x < metadata.Width; x++)
{
double longitude = metadata.DataStartLon + (metadata.pixelSizeX * x);
float heightValue = 0;
switch (metadata.SampleFormat)
{
case RasterSampleFormat.FLOATING_POINT:
heightValue = BitConverter.ToSingle(byteScanline, x * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.INTEGER:
heightValue = BitConverter.ToInt16(byteScanline, x * metadata.BitsPerSample / 8);
break;
case RasterSampleFormat.UNSIGNED_INTEGER:
heightValue = BitConverter.ToUInt16(byteScanline, x * metadata.BitsPerSample / 8);
break;
default:
throw new Exception("Sample format unsupported.");
}
if (heightValue < 32768)
{
heightMap.Minimum = Math.Min(metadata.MinimumAltitude, heightValue);
heightMap.Maximum = Math.Max(metadata.MaximumAltitude, heightValue);
}
else
{
heightValue = 0;
}
coords.Add(new GeoPoint(latitude, longitude, heightValue));
}
}
heightMap.Coordinates = coords;
return heightMap;
}
}
}