-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1961 lines (1378 loc) · 81.6 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 multiprocessing, glob, shutil, os, datetime, subprocess, math
import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cv2
import exiftool
import rasterio
import scipy.ndimage as ndimage
from skimage.transform import resize
from pathlib import Path
from ipywidgets import FloatProgress, Layout
from IPython.display import display
from micasense import imageset as imageset
from micasense import capture as capture
import micasense.imageutils as imageutils
import micasense.plotutils as plotutils
from micasense import panel
from micasense import image as image
import random
import cameratransform as ct
from rasterio.merge import merge
from tqdm import tqdm
from pyproj import CRS
from rasterio.transform import Affine
from rasterio.enums import Resampling
import contextily as cx
import rioxarray
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from pyproj import Transformer
from typing import Tuple
from matplotlib.image import AxesImage
from xyzservices import Bunch
# this isn't really good practice but there are a few deprecated tools in the Micasense stack so we'll ignore some of these warnings
import warnings
warnings.filterwarnings('ignore')
def function_that_warns():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
function_that_warns()
def write_metadata_csv(img_set, csv_output_path):
"""
This function grabs the EXIF metadata from img_set and writes it to outputPath/metadata.csv. Other metadata could be added based on what is needed in your workflow.
Parameters:
img_set: An ImageSet is a container for a group of Captures that are processed together. It is defined by running the ImageSet.from_directory() function found in Micasense's imageset.py
csv_output_path: A string containing the filepath to store metadata.csv containing image EXIF metadata
Returns:
A .csv of metadata for each image capture.
"""
def decdeg2dms(dd):
minutes, seconds = divmod(abs(dd) * 3600, 60)
degrees, minutes = divmod(minutes, 60)
degrees : float = degrees if dd >= 0 else -degrees
return (degrees, minutes, seconds)
lines = []
for i,capture in enumerate(img_set.captures):
fullOutputPath = os.path.join(csv_output_path, f'capture_{i+1}.tif')
width, height = capture.images[0].meta.image_size()
img : Image_micasense = capture.images[0]
lat, lon, alt = capture.location()
latdeg, londeg = decdeg2dms(lat)[0], decdeg2dms(lon)[0]
latdeg, latdir = (-latdeg, 'S') if latdeg < 0 else (latdeg, 'N')
londeg, londir = (-londeg, 'W') if londeg < 0 else (londeg, 'E')
datestamp, timestamp = capture.utc_time().strftime("%Y-%m-%d,%H:%M:%S").split(',')
resolution = capture.images[0].focal_plane_resolution_px_per_mm
focal_length = capture.images[0].focal_length
sensor_size = width / img.focal_plane_resolution_px_per_mm[0], height / img.focal_plane_resolution_px_per_mm[1]
data = {
'filename' : f'capture_{i+1}.tif',
'dirname' : fullOutputPath,
'DateStamp' : datestamp,
'TimeStamp' : timestamp,
'Latitude' : lat,
'LatitudeRef' : latdir,
'Longitude' : lon,
'LongitudeRef' : londir,
'Altitude' : alt,
'SensorX' : sensor_size[0],
'SensorY' : sensor_size[1],
'FocalLength' : focal_length,
'Yaw' : (capture.images[0].dls_yaw * 180 / math.pi) % 360,
'Pitch' : (capture.images[0].dls_pitch * 180 / math.pi) % 360,
'Roll' : (capture.images[0].dls_roll * 180 / math.pi) % 360,
'SolarElevation' : capture.images[0].solar_elevation,
'ImageWidth' : width,
'ImageHeight' : height,
'XResolution' : resolution[1],
'YResolution' : resolution[0],
'ResolutionUnits' : 'mm',
}
lines.append(list(data.values()))
header = list(data.keys())
fullCsvPath = os.path.join(csv_output_path,'metadata.csv')
df = pd.DataFrame(columns = header, data = lines)
df = df.set_index('filename')
#df['UTC-Time'] = pd.to_datetime(df['DateStamp'] +' '+ df['TimeStamp'],format="%Y:%m:%d %H:%M:%S")
df.to_csv(fullCsvPath)
return(fullCsvPath)
def load_images(img_list):
"""
This function loads all images in a directory as a multidimensional numpy array.
Parameters:
img_list: A list of .tif files, usually called by using glob.glob(filepath)
Returns:
A multidimensional numpy array of all image captures in a directory
"""
all_imgs = []
for im in img_list:
with rasterio.open(im, 'r') as src:
all_imgs.append(src.read())
return(np.array(all_imgs))
def load_img_fn_and_meta(csv_path, count=10000, start=0, random = False):
"""
This function returns a pandas dataframe of captures and associated metadata with the options of how many to list and what number of image to start on.
Parameters:
csv_path: A string containing the filepath
count: The amount of images to load. Default is 10000
start: The image to start loading from. Default is 0 (first image the .csv).
random: A boolean to load random images. Default is False
Returns:
Pandas dataframe of image metadata
"""
df = pd.read_csv(csv_path)
df = df.set_index('filename')
#df['UTC-Time'] = pd.to_datetime(df['UTC-Time'])
# cut off if necessary
df = df.iloc[start:start+count] if not random else df.loc[np.random.choice(df.index, count)]
return(df)
def retrieve_imgs_and_metadata(img_dir, count=10000, start=0, altitude_cutoff = 0, sky=False, random=False):
"""
This function is the main interface we expect the user to use when grabbing a subset of imagery from any stage in processing. This returns the images as a numpy array and metadata as a pandas dataframe.
Parameters:
img_dir: A string containing the directory filepath of images to be retrieved
count: The amount of images you want to list. Default is 10000
start: The number of image to start on. Default is 0 (first image in img_dir).
random: A boolean to load random images. Default is False
Returns:
A multidimensional numpy array of all image captures in a directory and a Pandas dataframe of image metadata.
"""
if sky:
csv_path = os.path.join(img_dir, 'metadata.csv')
else:
csv_path = os.path.join(os.path.dirname(img_dir), 'metadata.csv')
df = load_img_fn_and_meta(csv_path, count=count, start=start, random=random)
# apply altitiude threshold and set IDs as the indez
df = df[df['Altitude'] > altitude_cutoff]
# this grabs the filenames from the subset of the dataframe we've selected, then preprends the image_dir that we want.
# the filename is the index
all_imgs = load_images([os.path.join(img_dir,fn) for fn in df.index.values])
return(all_imgs, df)
def get_warp_matrix(img_capture, match_index=0, warp_mode = cv2.MOTION_HOMOGRAPHY, pyramid_levels = 1, max_alignment_iterations = 50):
"""
This function uses the MicaSense imageutils.align_capture() function to determine an alignment (warp) matrix of a single capture that can be applied to all images. From MicaSense: "For best alignment results it's recommended to select a capture which has features which visible in all bands. Man-made objects such as cars, roads, and buildings tend to work very well, while captures of only repeating crop rows tend to work poorly. Remember, once a good transformation has been found for flight, it can be generally be applied across all of the images." Ref: https://github.com/micasense/imageprocessing/blob/master/Alignment.ipynb
Parameters:
img_capture: A capture is a set of images taken by one MicaSense camera which share the same unique capture identifier (capture_id). These images share the same filename prefix, such as IMG_0000_*.tif. It is defined by running ImageSet.from_directory().captures.
match_index: Index of the band. Default is 0.
warp_mode: MOTION_HOMOGRAPHY or MOTION_AFFINE. For Altum images only use MOTION_HOMOGRAPHY
pyramid_levels: Default is 1. For images with RigRelatives, setting this to 0 or 1 may improve alignment
max_alignment_iterations: The maximum number of solver iterations.
Returns:
A numpy.ndarray of the warp matrix from a single image capture.
"""
print("Aligning images. Depending on settings this can take from a few seconds to many minutes")
# Can potentially increase max_iterations for better results, but longer runtimes
warp_matrices, alignment_pairs = imageutils.align_capture(img_capture,
ref_index = match_index,
max_iterations = max_alignment_iterations,
warp_mode = warp_mode,
pyramid_levels = pyramid_levels)
return(warp_matrices)
def save_images(img_set, img_output_path, thumbnailPath, warp_img_capture, generateThumbnails=True, overwrite_lt_lw=False):
"""
This function processes each capture in an imageset to apply a warp matrix and save new .tifs with units of radiance (W/sr/nm) and optional RGB .jpgs.
Parameters:
img_set: An ImageSet is a container for a group of Captures that are processed together. It is defined by running the ImageSet.from_directory() function found in Micasense's imageset.py
img_output_path: A string containing the filepath to store a new folder of radiance .tifs
thumbnailPath: A string containing the filepath to store a new folder of RGB thumnail .jpgs
warp_img_capture: A Capture chosen to align all images. Can be created by using Micasense's ImageSet-from_directory().captures function
generateThumbnails: Option to create RGB .jpgs of all the images. Default is True
overwrite_lt_lw: Option to overwrite lt and lw files that have been written previously. Default is False
Returns:
New .tif files for each capture in img_set with units of radiance (W/sr/nm) and optional new RGB thumbnail .jpg files for each capture.
"""
warp_matrices = get_warp_matrix(warp_img_capture)
if not os.path.exists(img_output_path):
os.makedirs(img_output_path)
if generateThumbnails and not os.path.exists(thumbnailPath):
os.makedirs(thumbnailPath)
start = datetime.datetime.now()
for i,capture in enumerate(img_set.captures):
outputFilename = 'capture_' + str(i+1) + '.tif'
thumbnailFilename = 'capture_' + str(i+1) + '.jpg'
fullOutputPath = os.path.join(img_output_path, outputFilename)
fullThumbnailPath= os.path.join(thumbnailPath, thumbnailFilename)
if (not os.path.exists(fullOutputPath)) or overwrite_lt_lw:
if(len(capture.images) == len(img_set.captures[0].images)):
capture.dls_irradiance = None
capture.compute_undistorted_radiance()
capture.create_aligned_capture(irradiance_list=None, img_type= 'radiance', warp_matrices=warp_matrices)
capture.save_capture_as_stack(fullOutputPath, sort_by_wavelength=True)
if generateThumbnails:
capture.save_capture_as_rgb(fullThumbnailPath)
capture.clear_image_data()
end = datetime.datetime.now()
print("Saving time: {}".format(end-start))
print("Alignment+Saving rate: {:.2f} images per second".format(float(len(img_set.captures))/float((end-start).total_seconds())))
return(True)
def process_micasense_images(project_dir, warp_img_dir=None, overwrite_lt_lw=False, sky=False):
"""
This function is wrapper function for the save_images() function to read in an image directory and produce new .tifs with units of radiance (W/sr/nm).
Parameters:
project_dir: a string containing the filepath of the raw .tifs
warp_img_dir: a string containing the filepath of the capture to use to create the warp matrix
overwrite_lt_lw: Option to overwrite lt and lw files that have been written previously. Default is False
sky: Option to run raw sky captures to collected Lsky. If True, the save_images() is run on raw .tif files and saves new .tifs in sky_lt directories. If False, save_images() is run on raw .tif files and saves new .tifs in lt directories.
Returns:
New .tif files for each capture in image directory with units of radiance (W/sr/nm) and optional new RGB thumbnail .jpg files for each capture.
"""
if sky:
img_dir = project_dir+'/raw_sky_imgs'
else:
img_dir = project_dir+'/raw_water_imgs'
imgset = imageset.ImageSet.from_directory(img_dir)
if warp_img_dir:
warp_img_capture = imageset.ImageSet.from_directory(warp_img_dir).captures[0]
print('used warp dir', warp_img_dir)
else:
warp_img_capture = imgset.captures[0]
# just have the sky images go into a different dir and the water imgs go into a default 'lt_imgs' dir
if sky:
outputPath = os.path.join(project_dir,'sky_lt_imgs')
output_csv_path = outputPath
thumbnailPath = os.path.join(project_dir, 'sky_lt_thumbnails')
else:
outputPath = os.path.join(project_dir,'lt_imgs')
output_csv_path = project_dir
thumbnailPath = os.path.join(project_dir, 'lt_thumbnails')
if save_images(imgset, outputPath, thumbnailPath, warp_img_capture, overwrite_lt_lw=overwrite_lt_lw
) == True:
print("Finished saving images.")
fullCsvPath = write_metadata_csv(imgset, output_csv_path)
print("Finished saving image metadata.")
return(outputPath)
######## workflow functions ########
def mobley_rho_method(sky_lt_dir, lt_dir, lw_dir, rho = 0.028):
"""
This function calculates water leaving radiance (Lw) by multiplying a single (or small set of) sky radiance (Lsky) images by a single rho value. The default is rho = 0.028, which is based off recommendations described in Mobley, 1999. This approach should only be used if sky conditions are not changing substantially during the flight and winds are less than 5 m/s.
Parameters:
sky_lt_dir: A string containing the directory filepath of sky_lt images
lt_dir: A string containing the directory filepath of lt images
lw_dir: A string containing the directory filepath of new lw images
rho = The effective sea-surface reflectance of a wave facet. The default 0.028
Returns:
New Lw .tifs with units of W/sr/nm
"""
# grab the first ten of these images, average them, then delete this from memory
sky_imgs, sky_img_metadata = retrieve_imgs_and_metadata(sky_lt_dir, count=10, start=0, altitude_cutoff=0, sky=True)
lsky_median = np.median(sky_imgs,axis=(0,2,3)) # here we want the median of each band
del sky_imgs # free up the memory
# go through each Lt image in the dir and subtract out rho*lsky to account for sky reflection
for im in glob.glob(lt_dir + "/*.tif"):
with rasterio.open(im, 'r') as Lt_src:
profile = Lt_src.profile
profile['count']=5
lw_all = []
for i in range(1,6):
# todo this is probably faster if we read them all and divide by the vector
lt = Lt_src.read(i)
lw = lt - (rho*lsky_median[i-1])
lw_all.append(lw) #append each band
stacked_lw = np.stack(lw_all) #stack into np.array
#write new stacked lw tifs
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(lw_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_lw)
return(True)
def blackpixel_method(sky_lt_dir, lt_dir, lw_dir):
"""
This function calculates water leaving radiance (Lw) by applying the black pixel assumption which assumes Lw in the NIR is negligable due to strong absorption of water. Therefore, total radiance (Lt) in the NIR is considered to be solely surface reflected light (Lsr) , which allows rho to be calculated if sky radiance (Lsky) is known. This method should only be used for waters where there is little to none NIR signal (i.e. Case 1 waters). The assumption tends to fail in more turbid waters where high concentrations of particles enhance backscattering and Lw in the NIR (i.e. Case 2 waters).
Parameters:
sky_lt_dir: A string containing the directory filepath of sky_lt images
lt_dir: A string containing the directory filepath of lt images
lw_dir: A string containing the directory filepath of new lw images
Returns:
New Lw .tifs with units of W/sr/nm
"""
# grab the first ten of these images, average them, then delete this from memory
sky_imgs, sky_img_metadata = retrieve_imgs_and_metadata(sky_lt_dir, count=10, start=0, altitude_cutoff=0, sky=True)
lsky_median = np.median(sky_imgs,axis=(0,2,3)) # here we want the median of each band
del sky_imgs
for im in glob.glob(lt_dir + "/*.tif"):
with rasterio.open(im, 'r') as Lt_src:
profile = Lt_src.profile
profile['count']=5
Lt = Lt_src.read(4)
rho = Lt/lsky_median[4-1]
lw_all = []
for i in range(1,6):
# todo this is probably faster if we read them all and divide by the vector
lt = Lt_src.read(i)
lw = lt - (rho*lsky_median[i-1])
lw_all.append(lw) #append each band
stacked_lw = np.stack(lw_all) #stack into np.array
#write new stacked lw tifs
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(lw_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_lw)
return(True)
def hedley_method(lt_dir, lw_dir, random_n=10):
"""
This function calculates water leaving radiance (Lw) by modelling a constant 'ambient' NIR brightness level which is removed from all pixels across all bands. An ambient NIR level is calculated by averaging the minimum 10% of Lt(NIR) across a random subset images. This value represents the NIR brightness of a pixel with no sun glint. A linear relationship between Lt(NIR) amd the visible bands (Lt) is established, and for each pixel, the slope of this line is multiplied by the difference between the pixel NIR value and the ambient NIR level.
Parameters:
lt_dir: A string containing the directory filepath of lt images
lw_dir: A string containing the directory filepath of new lw images
random_n: The amount of random images to calculate ambient NIR level. Default is 10.
Returns:
New Lw .tifs with units of W/sr/nm
"""
lt_all = []
rand = random.sample(glob.glob(lt_dir + "/*.tif"), random_n) #open random n files. n is selected by user in process_raw_to_rrs
for im in rand:
with rasterio.open(im, 'r') as lt_src:
profile = lt_src.profile
lt = lt_src.read()
lt_all.append(lt)
stacked_lt = np.stack(lt_all)
stacked_lt_reshape = stacked_lt.reshape(*stacked_lt.shape[:-2], -1) #flatten last two dims
#apply linear regression between NIR and visible bands
min_lt_NIR = []
for i in range(len(rand)):
min_lt_NIR.append(np.percentile(stacked_lt_reshape[i,4,:], .1)) #calculate minimum 10% of Lt(NIR)
mean_min_lt_NIR = np.mean(min_lt_NIR) #take mean of minimum 10% of random Lt(NIR)
all_slopes = []
for i in range(len(glob.glob(lt_dir + "/*.tif"))):
im = glob.glob(lt_dir + "/*.tif")[i]
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(im, 'r') as lt_src:
profile = lt_src.profile
lt = lt_src.read()
lt_reshape = lt.reshape(*lt.shape[:-2], -1) #flatten last two dims
lw_all = []
for j in range(0,5):
slopes = np.polyfit(lt_reshape[4,:], lt_reshape[j,:], 1)[0] #calculate slope between NIR and all bands of random files
all_slopes.append(slopes)
#calculate Lw (Lt - b(Lt(NIR)-min(Lt(NIR))))
lw = lt[j,:,:] - all_slopes[j]*(lt[4,:,:]-mean_min_lt_NIR)
lw_all.append(lw)
stacked_lw = np.stack(lw_all) #stack into np.array
profile['count']=5
#write new stacked Rrs tif w/ reflectance units
with rasterio.open(os.path.join(lw_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_lw)
return(True)
def panel_ed(panel_dir, lw_dir, rrs_dir, output_csv_path):
"""
This function calculates remote sensing reflectance (Rrs) by dividing downwelling irradiance (Ed) from the water leaving radiance (Lw) .tifs. Ed is calculated from the calibrated reflectance panel. This method does not perform well when light is variable such as partly cloudy days. It is recommended to use in the case of a clear, sunny day.
Parameters:
panel_dir: A string containing the directory filepath of the panel image captures
lw_dir: A string containing the directory filepath of lw images
rrs_dir: A string containing the directory filepath of new rrs images
output_csv_path: A string containing the filepath to save Ed measurements (mW/m2/nm) calculated from the panel
Returns:
New Rrs .tifs with units of sr^-1
New .csv file with average Ed measurements (mW/m2/nm) calculated from image cpatures of the calibrated reflectance panel
"""
panel_imgset = imageset.ImageSet.from_directory(panel_dir).captures
panels = np.array(panel_imgset)
ed_data = []
ed_columns = ['image', 'ed_475', 'ed_560', 'ed_668', 'ed_717', 'ed_842']
for i in range(len(panels)):
#calculate panel Ed from every panel capture
ed = np.array(panels[i].panel_irradiance()) # this function automatically finds the panel albedo and uses that to calcuate Ed, otherwise raises an error
ed[3], ed[4] = ed[4], ed[3] #flip last two bands
ed_row = ['capture_'+str(i+1)]+[np.mean(ed[0])]+[np.mean(ed[1])]+[np.mean(ed[2])]+[np.mean(ed[3])]+[np.mean(ed[4])]
ed_data.append(ed_row)
ed_data = pd.DataFrame.from_records(ed_data, index='image', columns = ed_columns)
ed_data.to_csv(output_csv_path+'/panel_ed.csv')
# now divide the lw_imagery by Ed to get rrs
# go through each Lt image in the dir and divide it by the lsky
for im in glob.glob(lw_dir + "/*.tif"):
with rasterio.open(im, 'r') as Lw_src:
profile = Lw_src.profile
profile['count']=5
rrs_all = []
# could vectorize this for speed
for i in range(1,6):
lw = Lw_src.read(i)
rrs = lw/ed[i-1]
rrs_all.append(rrs) #append each band
stacked_rrs = np.stack(rrs_all) #stack into np.array
#write new stacked Rrs tifs w/ Rrs units
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(rrs_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_rrs)
return(True)
def dls_ed(raw_water_dir, lw_dir, rrs_dir, output_csv_path, panel_dir=None, dls_corr=False):
"""
This function calculates remote sensing reflectance (Rrs) by dividing downwelling irradiance (Ed) from the water leaving radiance (Lw) .tifs. Ed is derived from the downwelling light sensor (DLS), which is collected at every image capture. This method does not perform well when light is variable such as partly cloudy days. It is recommended to use in overcast, completely cloudy conditions. A DLS correction can be optionally applied to tie together DLS and panel Ed measurements. In this case, a compensation factor derived from the calibration reflectance panel is applied to DLS Ed measurements.The defualt is False.
Parameters:
raw_water_dir: A string containing the directory filepath of the raw water images
lw_dir: A string containing the directory filepath of lw images
rrs_dir: A string containing the directory filepath of new rrs images
output_csv_path: A string containing the filepath to save Ed measurements (mW/m2/nm) derived from the DLS
panel_dir: A string containing the filepath of panel images. Only need if dls_corr=True.
dls_corr: Option to apply compensation factor from calibration reflectance panel to DLS Ed measurements. Default is False.
Returns:
New Rrs .tifs with units of sr^-1
New .csv file with average Ed measurements (mW/m2/nm) calculated from DLS measurements
"""
capture_imgset = imageset.ImageSet.from_directory(raw_water_dir).captures
ed_data = []
ed_columns = ['image', 'ed_475', 'ed_560', 'ed_668', 'ed_717', 'ed_842']
if not dls_corr:
for i,capture in enumerate(capture_imgset):
ed = capture.dls_irradiance()
ed[3], ed[4] = ed[4], ed[3] #flip last two bands (red edge and NIR)
ed_row = ['capture_'+str(i+1)]+[np.mean(ed[0]*1000)]+[np.mean(ed[1]*1000)]+[np.mean(ed[2]*1000)]+[np.mean(ed[3]*1000)]+[np.mean(ed[4]*1000)] #multiply by 1000 to scale to mW
ed_data.append(ed_row)
ed_data_df = pd.DataFrame.from_records(ed_data, index='image', columns = ed_columns)
ed_data_df.to_csv(output_csv_path+'/dls_ed.csv')
if dls_corr:
panel_imgset = imageset.ImageSet.from_directory(panel_dir).captures
panels = np.array(panel_imgset)
panel_ed_data = []
dls_ed_data = []
for i, capture in enumerate(panels):
#calculate panel Ed from every panel capture
panel_ed = np.array(panels[i].panel_irradiance()) # this function automatically finds the panel albedo and uses that to calcuate Ed, otherwise raises an error
panel_ed[3], panel_ed[4] = panel_ed[4], panel_ed[3] #flip last two bands
panel_ed_row = ['capture_'+str(i+1)]+[np.mean(panel_ed[0])]+[np.mean(panel_ed[1])]+[np.mean(panel_ed[2])]+[np.mean(panel_ed[3])]+[np.mean(panel_ed[4])] #multiply by 1000 to scale to mW (but want ed to still be in W to divide by Lw which is in W)
panel_ed_data.append(panel_ed_row)
#calculate DLS Ed from every panel capture
dls_ed = capture.dls_irradiance()
dls_ed[3], dls_ed[4] = dls_ed[4], dls_ed[3] #flip last two bands (red edge and NIR)
dls_ed_row = ['capture_'+str(i+1)]+[np.mean(dls_ed[0]*1000)]+[np.mean(dls_ed[1]*1000)]+[np.mean(dls_ed[2]*1000)]+[np.mean(dls_ed[3]*1000)]+[np.mean(dls_ed[4]*1000)] #multiply by 1000 to scale to mW
dls_ed_data.append(dls_ed_row)
dls_ed_corr = np.array(panel_ed)/(np.array(dls_ed[0:5])*1000)
# this is the DLS ed corrected by the panel correction factor
dls_ed_corr_data = []
for i,capture in enumerate(capture_imgset):
ed = capture.dls_irradiance()
ed = (ed[0:5]*dls_ed_corr)*1000
ed = np.append(ed, [0]) #add zero because other ed ends with a 0
dls_ed_corr_row = ['capture_'+str(i+1)]+[ed[0]]+[ed[1]]+[ed[2]]+[ed[3]]+[ed[4]]
dls_ed_corr_data.append(dls_ed_corr_row)
dls_ed_corr_data_df = pd.DataFrame.from_records(dls_ed_corr_data, index='image', columns = ed_columns)
dls_ed_corr_data_df.to_csv(output_csv_path+'/dls_corr_ed.csv')
# now divide the lw_imagery by ed to get rrs
# go through each Lt image in the dir and divide it by the lsky
for idx, im in enumerate(glob.glob(lw_dir + "/*.tif")):
with rasterio.open(im, 'r') as Lw_src:
profile = Lw_src.profile
profile['count']=5
rrs_all = []
# could vectorize this for speed
for i in range(1,6):
lw = Lw_src.read(i)
if dls_corr:
rrs = lw/dls_ed_corr_data[idx][i]
else:
rrs = lw/ed_data[idx][i]
rrs_all.append(rrs) #append each band
stacked_rrs = np.stack(rrs_all) #stack into np.array
#write new stacked Rrs tifs w/ Rrs units
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(rrs_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_rrs)
return(True)
# glint removal
def rrs_threshold_pixel_masking(rrs_dir, masked_rrs_dir, nir_threshold = 0.01, green_threshold = 0.005):
"""
This function masks pixels based on user supplied Rrs thresholds in an effort to remove instances of specular sun glint, shadowing, or adjacent land when present in the images.
Parameters:
rrs_dir: A string containing the directory filepath to write the new masked .tifs
masked_rrs_dir: A string containing the name of the directory to store masked Rrs images.
nir_threshold: An Rrs(NIR) value where pixels above this will be masked. Default is 0.01. These are usually pixels of specular sun glint or land features.
green_threshold: A Rrs(green) value where pixels below this will be masked. Default is 0.005. These are usually pixels of vegetation shadowing.
Returns:
New masked Rrs.tifs with units of sr^-1
"""
# go through each rrs image in the dir and mask pixels > nir_threshold and < green_threshold
for im in glob.glob(rrs_dir + "/*.tif"):
with rasterio.open(im, 'r') as rrs_src:
profile = rrs_src.profile
profile['count']=5
rrs_mask_all = []
nir = rrs_src.read(5)
green = rrs_src.read(2)
nir[nir > nir_threshold] = np.nan
green[green < green_threshold] = np.nan
nir_nan_index = np.isnan(nir)
green_nan_index = np.isnan(green)
#filter nan pixel indicies across all bands
for i in range(1,6):
rrs_mask = rrs_src.read(i)
rrs_mask[nir_nan_index] = np.nan
rrs_mask[green_nan_index] = np.nan
rrs_mask_all.append(rrs_mask)
stacked_rrs_mask = np.stack(rrs_mask_all) #stack into np.array
#write new stacked rrs tifs
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(masked_rrs_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_rrs_mask)
return(True)
def rrs_std_pixel_masking(rrs_dir, masked_rrs_dir, num_images=10, mask_std_factor=1):
"""
This function masks pixels based on a user supplied value in an effort to remove instances of specular sun glint. The mean and standard deviation of NIR values from the first N images is calculated and any pixels containing an NIR value > mean + std*mask_std_factor is masked across all bands. The lower the mask_std_factor, the more pixels will be masked.
Parameters:
rrs_dir: A string containing the directory filepath of images to be processed
masked_rrs_dir: A string containing the directory filepath to write the new masked .tifs
num_images: Number of images in the dataset to calculate the mean and std of NIR. Default is 10.
mask_std_factor: A factor to multiply to the standard deviation of NIR values. Default is 1.
Returns:
New masked .tifs
"""
# grab the first num_images images, finds the mean and std of NIR, then anything times the glint factor is classified as glint
rrs_imgs, _ = retrieve_imgs_and_metadata(rrs_dir, count=num_images, start=0, altitude_cutoff=0, random=True)
rrs_nir_mean = np.nanmean(rrs_imgs,axis=(0,2,3))[4] # mean of NIR band
rrs_nir_std = np.nanstd(rrs_imgs,axis=(0,2,3))[4] # std of NIR band
print('The mean and std of Rrs from first N images is: ', rrs_nir_mean, rrs_nir_std)
print('Pixels will be masked where Rrs(NIR) > ', rrs_nir_mean+rrs_nir_std*mask_std_factor)
del rrs_imgs # free up the memory
# go through each Rrs image in the dir and mask any pixels > mean+std*glint factor
for im in glob.glob(rrs_dir + "/*.tif"):
with rasterio.open(im, 'r') as rrs_src:
profile = rrs_src.profile
profile['count']=5
rrs_deglint_all = []
rrs_nir_deglint = rrs_src.read(5) #nir band
rrs_nir_deglint[rrs_nir_deglint > (rrs_nir_mean+rrs_nir_std*mask_std_factor)] = np.nan
nan_index = np.isnan(rrs_nir_deglint)
#filter nan pixel indicies across all bands
for i in range(1,6):
rrs_deglint = rrs_src.read(i)
rrs_deglint[nan_index] = np.nan
rrs_deglint_all.append(rrs_deglint) #append all for each band
stacked_rrs_deglint = np.stack(rrs_deglint_all) #stack into np.array
#write new stacked tifs
im_name = os.path.basename(im) # we're grabbing just the .tif file name instead of the whole path
with rasterio.open(os.path.join(masked_rrs_dir, im_name), 'w', **profile) as dst:
dst.write(stacked_rrs_deglint)
return(True)
def process_raw_to_rrs(main_dir, rrs_dir_name, output_csv_path, lw_method='mobley_rho_method', mask_pixels=False, random_n=10, pixel_masking_method='value_threshold', mask_std_factor=1, nir_threshold=0.01, green_threshold=0.005, ed_method='dls_ed', overwrite_lt_lw=False, clean_intermediates=True):
"""
This functions is the main processing script that processs raw imagery to units of remote sensing reflectance (Rrs). Users can select which processing parameters to use to calculate Rrs.
Parameters:
main_dir: A string containing the main image directory
rrs_dir_name: A string containing the directory filepath of new rrs images
output_csv_path: A string containing the filepath to write the metadata.csv
lw_method: Method used to calculate water leaving radiance. Default is mobley_rho_method().
random_n: The amount of random images to calculate ambient NIR level. Default is 10. Only need if lw_method = 'hedley_method'
mask_pixels: Option to mask pixels containing specular sun glint, shadowing, adjacent vegetation, etc. Default is False.
pixel_masking_method: Method to mask pixels. Options are 'value_threshold' or 'std_threshold'. Default is value_threshold.
mask_std_factor: A factor to multiply to the standard deviation of NIR values. Default is 1. Only need if pixel_masking_method = 'std_threshold'
nir_threshold: An Rrs(NIR) value where pixels above this will be masked. Default is 0.01. These are usually pixels of specular sun glint or land features. Only need if pixel_masking_method = 'value_threshold'.
green_threshold: A Rrs(green) value where pixels below this will be masked. Default is 0.005. These are usually pixels of vegetation shadowing. Only need if pixel_masking_method = 'value_threshold'.
ed_method: Method used to calculate downwelling irradiance (Ed). Default is dls_ed().
overwrite_lt_lw: Option to overwrite lt and lw files that have been written previously. Default is False but this is only applied to the Lt images.
clean_intermediates: Option to erase intermediates of processing (Lt, Lw, unmasked Rrs)
Returns:
New Rrs tifs (masked or unmasked) with units of sr^-1.
"""
############################
#### setup the workspace ###
############################
# specify the locations of the different levels of imagery
# I do this partially so I can just change these pointers to the data and not have to copy it or have complex logic repeated
### os join here
raw_water_img_dir = os.path.join(main_dir,'raw_water_imgs')
raw_sky_img_dir = os.path.join(main_dir,'raw_sky_imgs')
lt_dir = os.path.join(main_dir,'lt_imgs')
sky_lt_dir = os.path.join(main_dir,'sky_lt_imgs')
lw_dir = os.path.join(main_dir,'lw_imgs')
panel_dir = os.path.join(main_dir, 'panel')
rrs_dir = os.path.join(main_dir, rrs_dir_name)
masked_rrs_dir = os.path.join(main_dir, 'masked_'+rrs_dir_name)
warp_img_dir = os.path.join(main_dir,'align_img')
# make all these directories if they don't already exist
all_dirs = [lt_dir, lw_dir, rrs_dir]
for directory in all_dirs:
Path(directory).mkdir(parents=True, exist_ok=True)
if mask_pixels == True:
Path(masked_rrs_dir).mkdir(parents=True, exist_ok=True)
# this makes an assumption that there is only one panel image put in this directory
panel_names = glob.glob(os.path.join(panel_dir, 'IMG_*.tif'))
files = os.listdir(raw_water_img_dir) # your directory path
num_bands = imageset.ImageSet.from_directory(warp_img_dir).captures[0].num_bands
print(f'Processing a total of {len(files)} images or {round(len(files)/num_bands)} captures.')
### convert raw imagery to radiance (Lt)
print("Converting raw images to radiance (raw -> Lt).")
process_micasense_images(main_dir, warp_img_dir=warp_img_dir, overwrite_lt_lw=overwrite_lt_lw, sky=False)
# deciding if we need to process raw sky images to radiance
if lw_method in ['mobley_rho_method','blackpixel_method']:
print("Converting raw sky images to radiance (raw sky -> Lsky).")
# we're also making an assumption that we don't need to align/warp these images properly because they'll be medianed
process_micasense_images(main_dir, warp_img_dir=None, overwrite_lt_lw=overwrite_lt_lw, sky=True)
##################################
### correct for surface reflected light ###
##################################
if lw_method == 'mobley_rho_method':
print('Applying the mobley_rho_method (Lt -> Lw).')
mobley_rho_method(sky_lt_dir, lt_dir, lw_dir)
elif lw_method == 'blackpixel_method':
print('Applying the blackpixel_method (Lt -> Lw)')
blackpixel_method(sky_lt_dir, lt_dir, lw_dir)
elif lw_method == 'hedley_method':
print('Applying the Hochberg/Hedley (Lt -> Lw)')
hedley_method(lt_dir, lw_dir, random_n)
else: # just change this pointer if we didn't do anything the lt over to the lw dir
print('Not doing any Lw calculation.')
lw_dir = lt_dir
#####################################
### normalize Lw by Ed to get Rrs ###
#####################################
if ed_method == 'panel_ed':
print('Normalizing by panel irradiance (Lw/Ed -> Rrs).')
panel_ed(panel_dir, lw_dir, rrs_dir, output_csv_path)
elif ed_method == 'dls_ed':
print('Normalizing by DLS irradiance (Lw/Ed -> Rrs).')
dls_ed(raw_water_img_dir, lw_dir, rrs_dir, output_csv_path)
elif ed_method == 'dls_and_panel_ed':
print('Normalizing by DLS corrected by panel irradiance (Lw/Ed -> Rrs).')
dls_ed(raw_water_img_dir, lw_dir, rrs_dir, output_csv_path, panel_dir=panel_dir, dls_corr = True)
else:
print('No other irradiance normalization methods implemented yet, panel_ed is recommended.')
return(False)
print('All data has been saved as Rrs using the ' + str(lw_method) + ' to calculate Lw and normalized by '+ str(ed_method)+ ' irradiance.')
########################################
### mask pixels in the imagery (from glint, vegetation, shadows) ###
########################################
if mask_pixels == True and pixel_masking_method == 'value_threshold':
print('Masking pixels using NIR and green Rrs thresholds')
rrs_threshold_pixel_masking(rrs_dir, masked_rrs_dir, nir_threshold=nir_threshold, green_threshold=green_threshold)
elif mask_pixels == True and pixel_masking_method == 'std_threshold':
print('Masking pixels using std Rrs(NIR)')
rrs_std_pixel_masking(rrs_dir, masked_rrs_dir, mask_std_factor = mask_std_factor)
else: # if we don't do the glint correction then just change the pointer to the lt_dir
print('Not masking pixels.')
################################################
### finalize and add point output ###
################################################
if clean_intermediates:
dirs_to_delete = [lt_dir, sky_lt_dir, lw_dir]
for d in dirs_to_delete:
shutil.rmtree(d,ignore_errors=True)
return(True)
############ water quality retrieval algorithms ############
def chl_hu(Rrsblue, Rrsgreen, Rrsred):
"""
This is the Ocean Color Index (CI) three-band reflectance difference algorithm (Hu et al. 2012). This should only be used for chlorophyll retrievals below 0.15 mg m^-3. Documentation can be found here https://oceancolor.gsfc.nasa.gov/atbd/chlor_a/. doi: 10.1029/2011jc007395
Parameters:
Rrsblue: numpy array of Rrs in the blue band.
Rrsgreen: numpy array of Rrs in the green band.
Rrsred: numpy array of Rrs in the red band.
Returns:
Numpy array of derived chlorophyll (mg m^-3).
"""
ci1 = -0.4909
ci2 = 191.6590
CI = Rrsgreen - ( Rrsblue + (560 - 475)/(668 - 475) * (Rrsred - Rrsblue) )
ChlCI = 10**(ci1 + ci2*CI)
return(ChlCI)
def chl_ocx(Rrsblue, Rrsgreen):
"""
This is the OCx algorithm which uses a fourth-order polynomial relationship (O'Reilly et al. 1998). This should be used for chlorophyll retrievals above 0.2 mg m^-3. Documentation can be found here https://oceancolor.gsfc.nasa.gov/atbd/chlor_a/. The coefficients for OC2 (OLI/Landsat 8) are used as default. doi: 10.1029/98JC02160.
Parameters:
Rrsblue: numpy array of Rrs in the blue band.
Rrsgreen: numpy array of Rrs in the green band.
Returns:
Numpy array of derived chlorophyll (mg m^-3).
"""
# L8 OC2 coefficients
a0 = 0.1977
a1 = -1.8117
a2 = 1.9743
a3 = 2.5635
a4 = -0.7218
log10chl = a0 + a1 * (np.log10(Rrsblue / Rrsgreen)) \
+ a2 * (np.log10(Rrsblue / Rrsgreen))**2 \
+ a3 * (np.log10(Rrsblue / Rrsgreen))**3 \
+ a4 * (np.log10(Rrsblue / Rrsgreen))**4
ocx = np.power(10, log10chl)
return(ocx)
def chl_hu_ocx(Rrsblue, Rrsgreen, Rrsred):
'''
This is the blended NASA chlorophyll algorithm which combines Hu color index (CI) algorithm (chl_hu) and the O'Reilly band ratio OCx algortihm (chl_ocx). This specific code is grabbed from https://github.com/nasa/HyperInSPACE. Documentation can be found here https://www.earthdata.nasa.gov/apt/documents/chlor-a/v1.0#introduction.
Parameters:
Rrsblue: numpy array of Rrs in the blue band.
Rrsgreen: numpy array of Rrs in the green band.
Rrsred: numpy array of Rrs in the red band.
Returns:
Numpy array of derived chlorophyll (mg m^-3).
'''
thresh = [0.15, 0.20]
a0 = 0.1977
a1 = -1.8117
a2 = 1.9743
a3 = 2.5635
a4 = -0.7218
ci1 = -0.4909
ci2 = 191.6590
log10chl = a0 + a1 * (np.log10(Rrsblue / Rrsgreen)) \
+ a2 * (np.log10(Rrsblue / Rrsgreen))**2 \
+ a3 * (np.log10(Rrsblue / Rrsgreen))**3 \
+ a4 * (np.log10(Rrsblue / Rrsgreen))**4
ocx = np.power(10, log10chl)
CI = Rrsgreen - ( Rrsblue + (560 - 475)/(668 - 475) * \
(Rrsred -Rrsblue) )
ChlCI = 10** (ci1 + ci2*CI)
if ChlCI.any() <= thresh[0]:
chlor_a = ChlCI
elif ChlCI.any() > thresh[1]:
chlor_a = ocx
else:
chlor_a = ocx * (ChlCI-thresh[0]) / (thresh[1]-thresh[0]) +\
ChlCI * (thresh[1]-ChlCI) / (thresh[1]-thresh[0])
return chlor_a
def chl_gitelson(Rrsred, Rrsrededge):
"""
This algorithm estimates chlorophyll a concentrations using a 2-band algorithm with coefficients from Gitelson et al. 2007. This algorithm is recommended for coastal (Case 2) waters. doi:10.1016/j.rse.2007.01.016
Parameters:
Rrsred: numpy array of Rrs in the red band.
Rrsrededge: numpy array of Rrs in the red edge band.
Returns:
Numpy array of derived chlorophyll (mg m^-3).
"""
chl = 59.826 * (Rrsrededge/Rrsred) - 17.546
return chl
######## TSM retrieval algs ######