-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.py
2089 lines (1819 loc) · 79.4 KB
/
utils.py
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
import inspect
import math
import os
import re
import zipfile
import warnings
import sys
import time
from glob import glob
from functools import partial
from itertools import chain
from shutil import get_terminal_size
from datetime import datetime
import cv2
import pyproj
import numpy as np
from lxml.etree import parse, fromstring
import rasterio
from rasterio.io import MemoryFile
from rasterio.transform import xy, rowcol, Affine
from rasterio import features
from rasterio.coords import BoundingBox
import rasterio.warp as warp
from rasterio.transform import xy, rowcol
from shapely.geometry import Point, box, shape
from shapely.geometry import Polygon, MultiPolygon, box
from shapely.ops import transform
class cached_property(object):
"""
Decorator that converts a method with a single self argument into a
property cached on the instance.
Optional ``name`` argument allows you to make cached properties of other
methods. (e.g. url = cached_property(get_absolute_url, name='url') )
"""
def __init__(self, func, name=None):
self.func = func
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
def __get__(self, instance, cls=None):
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res
class ProgressBar(object):
"""
A progress bar which can print the progress
modified from https://github.com/hellock/cvbase/blob/master/cvbase/progress.py
"""
def __init__(self, task_num=0, bar_width=50, start=True):
self.task_num = task_num
max_bar_width = self._get_max_bar_width()
self.bar_width = (bar_width if bar_width <= max_bar_width else max_bar_width)
self.completed = 0
if start:
self.start()
def _get_max_bar_width(self):
terminal_width, _ = get_terminal_size()
max_bar_width = min(int(terminal_width * 0.6), terminal_width - 50)
if max_bar_width < 10:
print('terminal width is too small ({}), please consider widen the terminal for better '
'progressbar visualization'.format(terminal_width))
max_bar_width = 10
return max_bar_width
def start(self):
if self.task_num > 0:
sys.stdout.write('[{}] 0/{}, elapsed: 0s, ETA:\n{}\n'.format(
' ' * self.bar_width, self.task_num, 'Start...'))
else:
sys.stdout.write('completed: 0, elapsed: 0s')
sys.stdout.flush()
self.start_time = time.time()
def update(self, msg='In progress...'):
self.completed += 1
elapsed = time.time() - self.start_time
fps = self.completed / elapsed
if self.task_num > 0:
percentage = self.completed / float(self.task_num)
eta = int(elapsed * (1 - percentage) / percentage + 0.5)
mark_width = int(self.bar_width * percentage)
bar_chars = '>' * mark_width + '-' * (self.bar_width - mark_width)
sys.stdout.write('\033[2F') # cursor up 2 lines
sys.stdout.write('\033[J') # clean the output (remove extra chars since last display)
sys.stdout.write('[{}] {}/{}, {:.1f} task/s, elapsed: {}s, ETA: {:5}s\n{}\n'.format(
bar_chars, self.completed, self.task_num, fps, int(elapsed + 0.5), eta, msg))
else:
sys.stdout.write('completed: {}, elapsed: {}s, {:.1f} tasks/s'.format(
self.completed, int(elapsed + 0.5), fps))
sys.stdout.flush()
# get image path list
IMG_EXTENSIONS = ['.TIF', '.tif', '.jp2']
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def get_paths_from_l8_dir(path_dir):
"""get landsat8 image path list from image folder"""
assert os.path.isdir(path_dir), '{:s} is not a valid directory'.format(path_dir)
l8_file_ls = sorted(glob(os.path.join(path_dir, '*T1', '*_MTL.txt')))
assert l8_file_ls, '{:s} has no valid image file'.format(path_dir)
return l8_file_ls
def get_paths_from_s2_dir(path_dir):
"""get sentinel2 image path list from image folder"""
assert os.path.isdir(path_dir), '{:s} is not a valid directory'.format(path_dir)
s2_file_ls = sorted(glob(os.path.join(path_dir, '*.zip')))
assert s2_file_ls, '{:s} has no valid image file'.format(path_dir)
return s2_file_ls
def get_paths_from_images(path):
"""get image path list from image folder"""
assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)
images = []
for dirpath, _, fnames in sorted(os.walk(path)):
for fname in sorted(fnames):
if is_image_file(fname):
img_path = os.path.join(dirpath, fname)
images.append(img_path)
assert images, '{:s} has no valid image file'.format(path)
return images
def get_image_paths(data_type, dataroot):
"""get image path list
support lmdb or image files"""
paths, infos = None, None
if dataroot is not None:
if data_type == 'lmdb':
paths, infos = get_paths_from_lmdb(dataroot)
elif data_type == 'img':
paths = sorted(get_paths_from_images(dataroot))
else:
raise NotImplementedError('data_type [{:s}] is not recognized.'.format(data_type))
return paths, infos
# read images
def _read_img_lmdb(env, key, size):
"""read image from lmdb with key (w/ and w/o fixed size)
size: (C, H, W) tuple"""
with env.begin(write=False) as txn:
buf = txn.get(key.encode('ascii'))
img_flat = np.frombuffer(buf, dtype=np.float32)
C, H, W = size
img = img_flat.reshape(C, H, W)
return img
def read_img(env, path, size=None):
"""read image by rasterio or from lmdb
return: Numpy float32, CHW, RGB, normalized by mean and std"""
if env is None: # img
with rasterio.open(path, 'r') as src:
img = src.read()
else:
img = _read_img_lmdb(env, path, size)
return img
def tif_to_png(tif_path, png_path=None, pmin=2.5, pmax=97.5):
with rasterio.open(tif_path, 'r') as src:
src_data = src.read()
c, h, w = src_data.shape
output = np.zeros((h, w, c), dtype='u1')
for i in range(c):
v_min = np.percentile(src_data[i], pmin)
v_max = np.percentile(src_data[i], pmax)
tem_arr = np.clip(src_data[i], v_min, v_max)
output[:, :, i] = np.round((tem_arr - v_min) * 255. / (v_max - v_min)).astype('u1')
save_path = png_path if png_path else tif_path.replace('.TIF', '.png')
cv2.imwrite(save_path, output[:, :, ::-1], [cv2.IMWRITE_PNG_COMPRESSION, 3])
# print("saving image to {}".format(save_path))
def sun_elevation(bounds, shape, date_collected, time_collected_utc):
"""
Given a raster's bounds + dimensions, calculate the
sun elevation angle in degrees for each input pixel
based on metadata from a Landsat MTL file
Parameters
-----------
bounds: BoundingBox
bounding box of the input raster
shape: tuple
tuple of (rows, cols) or (depth, rows, cols) for input raster
date_collected: str
Format: YYYY-MM-DD
time_collected_utc: str
Format: HH:MM:SS.SSSSSSSSZ
Returns
--------
ndarray
ndarray with shape = (rows, cols) with sun elevation
in degrees calculated for each pixel
"""
utc_time = parse_utc_string(date_collected, time_collected_utc)
if len(shape) == 3:
_, rows, cols = shape
else:
rows, cols = shape
lng, lat = _create_lnglats((rows, cols),
list(bounds))
decimal_hour = time_to_dec_hour(utc_time)
declination = calculate_declination(utc_time.timetuple().tm_yday)
return _calculate_sun_elevation(lng, lat, declination,
utc_time.timetuple().tm_yday,
decimal_hour)
def parse_utc_string(collected_date, collected_time_utc):
"""
Given a string in the format:
YYYY-MM-DD HH:MM:SS.SSSSSSSSZ
Parse and convert into a datetime object
Fractional seconds are ignored
Parameters
-----------
collected_date: str
Format: YYYY-MM-DD
collected_time_utc: str
Format: HH:MM:SS.SSSSSSSSZ
Returns
--------
datetime object
parsed scene center time
"""
utcstr = collected_date + ' ' + collected_time_utc
if not re.match(r'\d{4}\-\d{2}\-\d{2}\ \d{2}\:\d{2}\:\d{2}\.\d+Z',
utcstr):
raise ValueError("%s is an invalid utc time" % utcstr)
return datetime.strptime(
utcstr.split(".")[0],
"%Y-%m-%d %H:%M:%S")
def _create_lnglats(shape, bbox):
"""
Creates a (lng, lat) array tuple with cells that respectively
represent a longitude and a latitude at that location
Parameters
-----------
shape: tuple
the shape of the arrays to create
bbox: tuple or list
the bounds of the arrays to create in [w, s, e, n]
Returns
--------
(lngs, lats): tuple of (rows, cols) shape ndarrays
"""
rows, cols = shape
w, s, e, n = bbox
xCell = (e - w) / float(cols)
yCell = (n - s) / float(rows)
lat, lng = np.indices(shape, dtype=np.float32)
return ((lng * xCell) + w + (xCell / 2.0),
(np.flipud(lat) * yCell) + s + (yCell / 2.0))
def time_to_dec_hour(parsedtime):
"""
Calculate the decimal hour from a datetime object
Parameters
-----------
parsedtime: datetime object
Returns
--------
decimal hour: float
time in decimal hours
"""
return (parsedtime.hour +
(parsedtime.minute / 60.0) +
(parsedtime.second / 60.0 ** 2)
)
def calculate_declination(d):
"""
Calculate the declination of the sun in radians based on a given day.
As reference +23.26 degrees at the northern summer solstice, -23.26
degrees at the southern summer solstice.
See: https://en.wikipedia.org/wiki/Position_of_the_Sun#Calculations
Parameters
-----------
d: int
days from midnight on January 1st
Returns
--------
declination in radians: float
the declination on day d
"""
return np.arcsin(
np.sin(np.deg2rad(23.45)) *
np.sin(np.deg2rad(360. / 365.) *
(d - 81))
)
def _calculate_sun_elevation(longitude, latitude, declination, day, utc_hour):
"""
Calculates the solar elevation angle
https://en.wikipedia.org/wiki/Solar_zenith_angle
Parameters
-----------
longitude: ndarray or float
longitudes of the point(s) to compute solar angle for
latitude: ndarray or float
latitudes of the point(s) to compute solar angle for
declination: float
declination of the sun in radians
day: int
days of the year with jan 1 as day = 1
utc_hour: float
decimal hour from a datetime object
Returns
--------
the solar elevation angle in degrees
"""
hour_angle = np.deg2rad(solar_angle(day, utc_hour, longitude))
latitude = np.deg2rad(latitude)
return np.rad2deg(np.arcsin(
np.sin(declination) *
np.sin(latitude) +
np.cos(declination) *
np.cos(latitude) *
np.cos(hour_angle)
))
def solar_angle(day, utc_hour, longitude):
"""
Given a day, utc decimal hour, and longitudes, compute the solar angle
for these longitudes
Parameters
-----------
day: int
days of the year with jan 1 as day = 1
utc_hour: float
decimal hour of the day in utc time to compute solar angle for
longitude: ndarray or float
longitude of the point(s) to compute solar angle for
Returns
--------
solar angle in degrees for these longitudes
"""
localtime = (longitude / 180.0) * 12 + utc_hour
lstm = 15 * (localtime - utc_hour)
B = np.deg2rad((360. / 365.) * (day - 81))
eot = (9.87 *
np.sin(2 * B) -
7.53 * np.cos(B) -
1.5 * np.sin(B))
return 15 * (localtime +
(4 * (longitude - lstm) + eot) / 60.0 - 12)
# -------------------------------------------------------------
# landsat8 tiles reader
class MetaData(object):
"""
A landsat metadata object. This class builds is attributes
from the names of each tag in the xml formatted .MTL files that
come with landsat data. So, any tag that appears in the MTL file
will populate as an attribute of landsat_metadata.
You can access explore these attributes by using, for example
.. code-block:: python
from dnppy import landsat
meta = landsat.landsat_metadata(my_filepath) # create object
from pprint import pprint # import pprint
pprint(vars(m)) # pretty print output
scene_id = meta.LANDSAT_SCENE_ID # access specific attribute
:param filename: the filepath to an MTL file.
copied from: https://github.com/NASA-DEVELOP/dnppy/tree/master/dnppy
"""
def __init__(self, filename):
"""
There are several critical attributes that keep a common
naming convention between all landsat versions, so they are
initialized in this class for good record keeping and reference
"""
# custom attribute additions
self.FILEPATH = filename
self.DATETIME_OBJ = None
# product metadata attributes
self.LANDSAT_SCENE_ID = None
self.DATA_TYPE = None
self.ELEVATION_SOURCE = None
self.OUTPUT_FORMAT = None
self.SPACECRAFT_ID = None
self.SENSOR_ID = None
self.WRS_PATH = None
self.WRS_ROW = None
self.NADIR_OFFNADIR = None
self.TARGET_WRS_PATH = None
self.TARGET_WRS_ROW = None
self.DATE_ACQUIRED = None
self.SCENE_CENTER_TIME = None
# image attributes
self.CLOUD_COVER = None
self.IMAGE_QUALITY_OLI = None
self.IMAGE_QUALITY_TIRS = None
self.ROLL_ANGLE = None
self.SUN_AZIMUTH = None
self.SUN_ELEVATION = None
self.EARTH_SUN_DISTANCE = None # calculated for Landsats before 8.
# read the file and populate the MTL attributes
self._read(filename)
def _read(self, filename):
""" reads the contents of an MTL file """
# if the "filename" input is actually already a metadata class object, return it back.
if inspect.isclass(filename):
return filename
fields = []
values = []
metafile = open(filename, 'r')
metadata = metafile.readlines()
for line in metadata:
# skips lines that contain "bad flags" denoting useless data AND lines
# greater than 1000 characters. 1000 character limit works around an odd LC5
# issue where the metadata has 40,000+ characters of whitespace
bad_flags = ["END", "GROUP"]
if not any(x in line for x in bad_flags) and len(line) <= 1000:
try:
line = line.replace(" ", "")
line = line.replace("\n", "")
field_name, field_value = line.split(' = ')
fields.append(field_name)
values.append(field_value)
except:
pass
for i in range(len(fields)):
# format fields without quotes,dates, or times in them as floats
if not any(['"' in values[i], 'DATE' in fields[i], 'TIME' in fields[i]]):
setattr(self, fields[i], float(values[i]))
else:
values[i] = values[i].replace('"', '')
setattr(self, fields[i], values[i])
# create datetime_obj attribute (drop decimal seconds)
dto_string = self.DATE_ACQUIRED + self.SCENE_CENTER_TIME
self.DATETIME_OBJ = datetime.strptime(dto_string.split(".")[0], "%Y-%m-%d%H:%M:%S")
# only landsat 8 includes sun-earth-distance in MTL file, so calculate it
# for the Landsats 4,5,7 using solar module.
# if not self.SPACECRAFT_ID == "LANDSAT_8":
#
# # use 0s for lat and lon, sun_earth_distance is not a function of any one location on earth.
# s = Solar(0, 0, self.DATETIME_OBJ, 0)
# self.EARTH_SUN_DISTANCE = s.get_rad_vector()
# print("Scene {0} center time is {1}".format(self.LANDSAT_SCENE_ID, self.DATETIME_OBJ))
class LandsatScene(object):
"""
Defines a landsat scene object. Used to track band filepaths
and pass raster objects to functions.
band filepaths are read from the MTL file and stored as a dict.
you may access them with
from dnppy import landsat
s = landsat.scene(MTL_path)
s[1] # the first band of scene "s"
s[2] # the second band of scene "s"
s["QA"] # the QA band of scene "s"
Development Note:
1) This is arcpy dependent, but in the future it should utilize
custom functions that emulate RasterToNumPyArray and the dnppy metadata
objects for all returns, thus eliminating all non-open source
dependencies
2) for good interchangability between landsat versions, it might be better
to construct a dict whos keys are color codes or even wavelength values
instead of band index numbers (which are do not correspond to similar colors
between landsat missions)
some codes are copied from: https://github.com/mapbox/rio-toa/tree/master/rio_toa
"""
def __init__(self, MTL_path, tif_dir=None):
"""
builds the scene.
In some cases, users may have their MTL file located somewhere other than
their landsat data. In this instance, users should input the path to
the landsat images as tif_dir.
"""
self.mtl_dir = os.path.dirname(MTL_path) # directory of MTL file
self.meta = MetaData(MTL_path) # dnppy landsat_metadata object
self.in_paths = {} # dict of filepaths to tifs
self.rasts = {} # dict of arcpy raster objects
self.profiles = {}
if not tif_dir:
self.tif_dir = self.mtl_dir
self._find_bands()
def read_data(self, idx):
if not isinstance(idx, list):
idx = [idx]
for i in idx:
tem_path = self.in_paths["B{0}".format(i)]
if os.path.isfile(tem_path):
if not "B{0}".format(i) in self.rasts:
with rasterio.open(tem_path) as src:
self.rasts["B{0}".format(i)] = src.read(1)
self.profiles["B{0}".format(i)] = src.profile
self.profiles["B{0}".format(i)]['bounds'] = src.bounds
self.profiles["B{0}".format(i)]['res'] = src.res
else:
raise NotImplementedError("file: {} doesn't exist".format(tem_path))
def get_DN(self, idx):
""" returns DN from indices """
if not "B{0}".format(idx) in self.rasts:
self.read_data(idx)
return self.rasts["B{0}".format(idx)]
def get_TOA(self, idx, per_pixel=True, clip=True):
dn_arr = self.get_DN(idx)
rows, cols = dn_arr.shape
profile = self.profiles["B{0}".format(idx)]
if per_pixel:
col_min, row_max, col_max, row_min = 0, profile['height'], profile['width'], 0
left, bottom = profile['transform'] * (col_min, row_max)
right, top = profile['transform'] * (col_max, row_min)
new_bound = warp.transform_bounds(profile['crs'], {'init': u'epsg:4326'}, left, bottom, right, top)
bbox = BoundingBox(*new_bound)
elevation = sun_elevation(bbox, (rows, cols), self.meta.DATE_ACQUIRED, self.meta.SCENE_CENTER_TIME)
else:
# We're doing whole-scene (instead of per-pixel) sun angle:
elevation = self.meta.SUN_ELEVATION
multi_f = getattr(self.meta, "REFLECTANCE_MULT_BAND_{0}".format(idx)) # multiplicative scaling factor
add_f = getattr(self.meta, "REFLECTANCE_ADD_BAND_{0}".format(idx)) # additive rescaling factor
toa = self._calculate_reflectance(dn_arr, multi_f, add_f, elevation)
if clip:
toa = np.clip(toa, 0, 1)
return toa
def xy(self, row, col, band, offset="center"):
"""Returns the coordinates ``(x, y)`` of a pixel at `row` and `col`.
The pixel's center is returned by default, but a corner can be returned
by setting `offset` to one of `ul, ur, ll, lr`.
Parameters
----------
row : int
Pixel row.
col : int
Pixel column.
band : int or str
Determines the transform to be used, because different bands may have different transform
offset : str, optional
Determines if the returned coordinates are for the center of the
pixel or for a corner.
Returns
-------
tuple
``(x, y)``
"""
if not "B{0}".format(band) in self.profiles:
self.read_data(band)
return xy(self.profiles["B{0}".format(band)]['transform'], row, col, offset=offset)
def index(self, x, y, band, op=math.floor, precision=None):
"""
Returns the (row, col) index of the pixel containing (x, y) given a
coordinate reference system.
Use an epsilon, magnitude determined by the precision parameter
and sign determined by the op function:
positive for floor, negative for ceil.
Parameters
----------
x : float
x value in coordinate reference system
y : float
y value in coordinate reference system
band : int or str
Determines the transform to be used, because different bands may have different transform
op : function, optional (default: math.floor)
Function to convert fractional pixels to whole numbers (floor,
ceiling, round)
precision : int, optional (default: None)
Decimal places of precision in indexing, as in `round()`.
Returns
-------
tuple
(row index, col index)
"""
if not "B{0}".format(band) in self.profiles:
self.read_data(band)
return rowcol(self.profiles["B{0}".format(band)]['transform'], x, y, op=op, precision=precision)
@staticmethod
def _calculate_reflectance(img, MR, AR, E, src_nodata=0):
"""Calculate top of atmosphere reflectance of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
R_raw = MR * Q + AR
R = R_raw / cos(Z) = R_raw / sin(E)
Z = 90 - E (in degrees)
where:
R_raw = TOA planetary reflectance, without correction for solar angle.
R = TOA reflectance with a correction for the sun angle.
MR = Band-specific multiplicative rescaling factor from the metadata
(REFLECTANCE_MULT_BAND_x, where x is the band number)
AR = Band-specific additive rescaling factor from the metadata
(REFLECTANCE_ADD_BAND_x, where x is the band number)
Q = Quantized and calibrated standard product pixel values (DN)
E = Local sun elevation angle. The scene center sun elevation angle
in degrees is provided in the metadata (SUN_ELEVATION).
Z = Local solar zenith angle (same angle as E, but measured from the
zenith instead of from the horizon).
Parameters
-----------
img: ndarray
array of input pixels of shape (rows, cols) or (rows, cols, depth)
MR: float or list of floats
multiplicative rescaling factor from scene metadata
AR: float or list of floats
additive rescaling factor from scene metadata
E: float or numpy array of floats
local sun elevation angle in degrees
Returns
--------
ndarray:
float32 ndarray with shape == input shape
"""
if np.any(E < 0.0):
raise ValueError("Sun elevation must be nonnegative "
"(sun must be above horizon for entire scene)")
input_shape = img.shape
if len(input_shape) > 2:
img = np.rollaxis(img, 0, len(input_shape))
rf = ((MR * img.astype(np.float32)) + AR) / np.sin(np.deg2rad(E))
if src_nodata is not None:
rf[img == src_nodata] = 0.0
if len(input_shape) > 2:
if np.rollaxis(rf, len(input_shape) - 1, 0).shape != input_shape:
raise ValueError(
"Output shape %s is not equal to input shape %s"
% (rf.shape, input_shape))
else:
return np.rollaxis(rf, len(input_shape) - 1, 0)
else:
return rf
def _find_bands(self):
"""
builds filepaths for band filenames from the MTL file
in the future, methods associated with landsat scenes,
(for example: NDVI calculation) could save rasters in the scene
directory with new suffixes then add attribute values to the MTL.txt
file for easy reading later, such as:
FILE_NAME_PROD_NDVI = [filepath to NDVI tif]
"""
# build a band list based on the landsat version
if self.meta.SPACECRAFT_ID == "LANDSAT_8":
bandlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# add in landsat 8s QA band with shortened name
QA_name = self.meta.FILE_NAME_BAND_QUALITY
self.in_paths["BQA"] = os.path.join(self.tif_dir, QA_name)
elif self.meta.SPACECRAFT_ID == "LANDSAT_7":
bandlist = [1, 2, 3, 4, 5, "6_VCID_1", "6_VCID_2", 7, 8]
elif self.meta.SPACECRAFT_ID == "LANDSAT_5":
bandlist = [1, 2, 3, 4, 5, 6, 7]
elif self.meta.SPACECRAFT_ID == "LANDSAT_4":
bandlist = [1, 2, 3, 4, 5, 6, 7]
else:
raise ValueError
# populate self.bands dict
for band in bandlist:
filename = getattr(self.meta, "FILE_NAME_BAND_{0}".format(band))
filepath = os.path.join(self.tif_dir, filename)
self.in_paths["B{0}".format(band)] = filepath
return
@staticmethod
def _capture_bits(arr, b1, b2):
width_int = int((b1 - b2 + 1) * "1", 2)
return ((arr >> b2) & width_int).astype('uint8')
def get_mask(self, kinds):
qa_vars = {
'fill': (0, 0),
'terrain': (1, 1),
'radiometricSaturation': (3, 2),
'cloud': (4, 4),
'cloudConf': (6, 5),
'cirrusConf': (8, 7),
'cloudShadowConf': (10, 9),
'snowIceConf': (12, 11),
}
if not isinstance(kinds, list):
kinds = [kinds]
qa_arr = self.get_DN('QA')
return [self._capture_bits(qa_arr, *qa_vars[kind]) for kind in kinds]
def get_surface_reflectance(self):
""" wraps dnppy.landsat.surface_reflecance functions and applies them to this scene"""
pass
def get_toa_reflectance(self):
""" wraps dnppy.landsat.toa_reflectance functions and applies them to this scene"""
pass
def get_ndvi(self):
""" wraps dnppy.landsat.ndvi functions and applies them to this scene"""
pass
def get_atsat_bright_temp(self):
""" wraps dnppy.atsat_bright_temp functions and applies them to this scene"""
pass
# -------------------------------------------------------------
"""
s2reader reads and processes Sentinel-2 L1C SAFE archives.
This module implements an easy abstraction to the SAFE data format used by the
Sentinel 2 misson of the European Space Agency (ESA)
most are copied from: https://github.com/ungarj/s2reader
"""
# sentinel2 granules reader
def s2_open(safe_file):
"""Return a SentinelDataSet object."""
if os.path.isdir(safe_file) or os.path.isfile(safe_file):
return SentinelDataSet(safe_file)
else:
raise IOError("file not found: %s" % safe_file)
BAND_IDS = [
"01", "02", "03", "04", "05", "06", "07", "08", "8A", "09", "10",
"11", "12"
]
class SentinelDataSet(object):
"""
Return SentinelDataSet object.
This object contains relevant metadata from the SAFE file and its
containing granules as SentinelGranule() object.
"""
def __init__(self, path):
"""Assert correct path and initialize."""
filename, extension = os.path.splitext(os.path.normpath(path))
if extension not in [".SAFE", ".ZIP", ".zip"]:
raise IOError("only .SAFE folders or zipped .SAFE folders allowed")
self.is_zip = True if extension in [".ZIP", ".zip"] else False
self.path = os.path.normpath(path)
if self.is_zip:
self._zipfile = zipfile.ZipFile(self.path, 'r')
self._zip_root = os.path.basename(filename)
if self._zip_root not in self._zipfile.namelist():
if not filename.endswith(".SAFE"):
self._zip_root = os.path.basename(filename) + ".SAFE/"
else:
self._zip_root = os.path.basename(filename) + "/"
if self._zip_root not in self._zipfile.namelist():
raise S2ReaderIOError("unknown zipfile structure")
self.manifest_safe_path = os.path.join(
self._zip_root, "manifest.safe")
else:
self._zipfile = None
self._zip_root = None
# Find manifest.safe.
self.manifest_safe_path = os.path.join(self.path, "manifest.safe")
if (
not os.path.isfile(self.manifest_safe_path) and
self.manifest_safe_path not in self._zipfile.namelist()
):
raise S2ReaderIOError(
"manifest.safe not found: %s" % self.manifest_safe_path
)
@cached_property
def _product_metadata(self):
if self.is_zip:
return fromstring(self._zipfile.read(self.product_metadata_path))
else:
return parse(self.product_metadata_path)
@cached_property
def _manifest_safe(self):
if self.is_zip:
return fromstring(self._zipfile.read(self.manifest_safe_path))
else:
return parse(self.manifest_safe_path)
@cached_property
def product_metadata_path(self):
"""Return path to product metadata XML file."""
data_object_section = self._manifest_safe.find("dataObjectSection")
for data_object in data_object_section:
# Find product metadata XML.
if data_object.attrib.get("ID") == "S2_Level-1C_Product_Metadata":
relpath = os.path.relpath(
next(data_object.iter("fileLocation")).attrib["href"])
try:
if self.is_zip:
abspath = os.path.join(self._zip_root, relpath)
assert abspath in self._zipfile.namelist()
else:
abspath = os.path.join(self.path, relpath)
assert os.path.isfile(abspath)
except AssertionError:
raise S2ReaderIOError(
"S2_Level-1C_product_metadata_path not found: {} ".format(abspath)
)
return abspath
@cached_property
def product_ID(self):
"""Find and returns "Product Start Time"."""
for element in self._product_metadata.iter("Product_Info"):
return element.find("PRODUCT_URI").text[:-5]
@cached_property
def product_start_time(self):
"""Find and returns "Product Start Time"."""
for element in self._product_metadata.iter("Product_Info"):
return element.find("PRODUCT_START_TIME").text
@cached_property
def product_stop_time(self):
"""Find and returns the "Product Stop Time"."""
for element in self._product_metadata.iter("Product_Info"):
return element.find("PRODUCT_STOP_TIME").text
@cached_property
def generation_time(self):
"""Find and returns the "Generation Time"."""
for element in self._product_metadata.iter("Product_Info"):
return element.findtext("GENERATION_TIME")
@cached_property
def processing_level(self):
"""Find and returns the "Processing Level"."""
for element in self._product_metadata.iter("Product_Info"):
return element.findtext("PROCESSING_LEVEL")
@cached_property
def product_type(self):
"""Find and returns the "Product Type"."""
for element in self._product_metadata.iter("Product_Info"):
return element.findtext("PRODUCT_TYPE")
@cached_property
def spacecraft_name(self):
"""Find and returns the "Spacecraft name"."""
for element in self._product_metadata.iter("Datatake"):
return element.findtext("SPACECRAFT_NAME")
@cached_property
def sensing_orbit_number(self):
"""Find and returns the "Sensing orbit number"."""
for element in self._product_metadata.iter("Datatake"):
return element.findtext("SENSING_ORBIT_NUMBER")
@cached_property
def sensing_orbit_direction(self):
"""Find and returns the "Sensing orbit direction"."""
for element in self._product_metadata.iter("Datatake"):
return element.findtext("SENSING_ORBIT_DIRECTION")
@cached_property
def product_format(self):
"""Find and returns the Safe format."""
for element in self._product_metadata.iter("Query_Options"):
return element.findtext("PRODUCT_FORMAT")
@cached_property
def quantification_value(self):
"""Find and returns the Safe format."""
for element in self._product_metadata.iter("Product_Image_Characteristics"):
return int(element.findtext("QUANTIFICATION_VALUE"))
@cached_property
def footprint(self):
"""Return product footprint."""
product_footprint = self._product_metadata.iter("Product_Footprint")
# I don't know why two "Product_Footprint" items are found.
for element in product_footprint:
global_footprint = None
for global_footprint in element.iter("Global_Footprint"):
coords = global_footprint.findtext("EXT_POS_LIST").split()
return _polygon_from_coords(coords)
@cached_property
def granules(self):
"""Return list of SentinelGranule objects."""
for element in self._product_metadata.iter("Product_Info"):
product_organisation = element.find("Product_Organisation")
if self.product_format == 'SAFE':
return [
SentinelGranule(_id.find("Granules"), self)
for _id in product_organisation.findall("Granule_List")
]
elif self.product_format == 'SAFE_COMPACT':
return [
SentinelGranuleCompact(_id.find("Granule"), self)
for _id in product_organisation.findall("Granule_List")
]
else:
raise Exception(
"PRODUCT_FORMAT not recognized in metadata file, found: '" +
str(self.product_format) +
"' accepted are 'SAFE' and 'SAFE_COMPACT'"
)
def granule_paths(self, band_id):
"""Return the path of all granules of a given band."""
band_id = str(band_id).zfill(2)
try:
assert isinstance(band_id, str)
assert band_id in BAND_IDS
except AssertionError:
raise AttributeError(
"band ID not valid: %s" % band_id
)
return [
granule.band_path(band_id)
for granule in self.granules