-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecreamos.m
1771 lines (1465 loc) · 67.4 KB
/
recreamos.m
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
function rout=recreamos( sat, indir, aoi, dopar )
%RECREAMOS REad, CRop, REproject, resAMple and mOSaic satellite imagery
% Inputs:
% sat=Satellite keyword argument. Sentinel-2=Sentinel-2 L1C (TOA), Landsat_8=Landsat 8 L1 (TOA),
% Landsat_8_SR=Landsat 8 L2 (SR), Landsat_7=Landsat 7 L1,
% RapidEye=RapidEye TOA, Planet=PlanetScope TOA.
% indir=(Relative) path to the input directory that contains the satellite
% image(s), either as one scene in the directory or multiple scenes in
% seperate numbered (i.e. 1,2,3 etc...) subdirectories.
% aoi=An "area of interest" structure that contains a rectangular
% bounding box defining the area of interest, defined by UTM coordinate
% vectors aoi.x and aoi.y, as well as the UTM zone.
% dopar=Switch (1/0) if the resampling should be performed using a
% parallel pool (1) or not (0). If the parallel switch is on then half
% the available clusters on the local parallel pool will be used.
% Outputs:
% rout=An output reflectance structure. Contains the following fields:
% r=An Ny x Nx x Nb array
%{
rout.r=r;
rout.x=x;
rout.y=y;
rout.t=mean(t);
rout.SE=mean(SE);
rout.delta=delta;
rout.utmz=rs(1).utmz;
rout.order=rs(1).order;
rout.source=rs(1).source;
%}
% By Kristoffer Aalstad (last revised: September 2018).
indir=[indir '/']; % Pad the input directory string with an extra / (can never have too many).
%% Part 1. Read, crop and reproject.
if strcmp('Planet',sat)
ris=r_PlanetScope(indir,aoi);
elseif strcmp('RapidEye',sat)
ris=r_RapidEye(indir,aoi);
elseif strcmp('Sentinel-2',sat)
ris=r_Sentinel_2(indir,aoi);
elseif strcmp('Landsat_7',sat)
ris=r_Landsat_7(indir,aoi);
elseif strcmp('Landsat_8',sat)
ris=r_Landsat_8(indir,aoi);
elseif strcmp('Landsat_8_SR',sat)
ris=r_Landsat_8_SR(indir,aoi);
elseif strcmp('Landsat_7_SR',sat)
ris=r_Landsat_7_SR(indir,aoi);
elseif strcmp('Sentinel-2_SR',sat)
ris=r_Sentinel_2_SR(indir,aoi);
else
error('Please specify a valid satellite constellation. Current options: Sentinel-2, Sentinel-2 SR, Landsat_8, Landsat_8_SR, Landsat_7, Landsat_7_SR, RapidEye, Planet')
end
%rout=ris;
%return
%% Part 2. Resample and mosaic.
rs=ris; clear ris;
ns=numel(rs);
delta=rs(1).delta;
nb=size(rs(1).r,3);
% Sort the scenes in order from north to south, and west to east if the
% northings are the same.
ulc=zeros(ns,1,'single');
np=0; % Number of pixels.
for s=1:ns
ulc(s,1)=rs(s).ulx;
ulc(s,2)=rs(s).uly;
np=np+numel(rs(s).X(:));
end
[~,order]=sortrows(ulc,[-2 1]); % Sort north to south first then west to east.
% Define the pixel centroids for all the scenes (in the right order).
Xr=zeros(np,1,'double'); Yr=zeros(np,1,'double');
rr=zeros(np,nb,'uint8');
% Find the maximum scale factor for across all the scenes for each band.
sf=zeros(nb,1);
for s=1:ns
for b=1:nb
if rs(s).sf(b)>sf(b)
sf(b)=rs(s).sf(b);
end
end
end
% Rescale and concatenate the scenes into a single array (called rr)
% to allow mosaicing.
here=1;
for s=1:ns
ind=order(s);
nps=numel(rs(ind).X(:));
these=here:(here-1+nps);
Xr(these)=rs(ind).X(:);
Yr(these)=rs(ind).Y(:);
for b=1:nb
temp=single(rs(ind).r(:,:,b)).*rs(ind).sf(b)./sf(b);
rr(these,b)=uint8(temp(:));
end
here=here+nps;
end
% Remove any missing data from the concatenated array.
% OBS! QA "bands" may have values of 0. So limit missing data to 0s in actual bands (b\in 1:6)
these=all(rr(:,1:6)>0,2);
Xr=Xr(these);
Yr=Yr(these);
rr=rr(these,:);
% Construct a regular grid and find the nearest neighbors.
mpx=mean(aoi.x); mpy=mean(aoi.y);
d=sqrt((Xr-mpx).^2+(Yr-mpy).^2);
mphere=find(d==min(d),1,'first');
xn=min(aoi.x)-3.*delta; xm=max(aoi.x)+3.*delta;
yn=min(aoi.y)-3.*delta; ym=max(aoi.y)+3.*delta;
xl=(Xr(mphere):-delta:xn)'; xl=flipud(xl);
xu=(Xr(mphere):delta:xm)';
x=[xl(1:end-1); xu];
yl=(Yr(mphere):-delta:yn)'; yl=flipud(yl);
yu=(Yr(mphere):delta:ym)';
y=[yl(1:end-1); yu]; y=flipud(y);
% Crop the grid to where you actually have data.
% I guess this part is problematic for S2? Fixed.
maxx=max(Xr)+0.*delta; minx=min(Xr)-0.*delta;
maxy=max(Yr)+0.*delta; miny=min(Yr)-0.*delta;
x=x(x>=minx&x<=maxx);
y=y(y>=miny&y<=maxy);
[X,Y]=meshgrid(x,y);
clear xl xu yl yu d
% Find NN
disp('Finding NN');
if dopar
c=parcluster('local');
nc=ceil(c.NumWorkers./4); % Maybe add factor 0.5 here to avoid using all!
p=gcp('nocreate');
if isempty(p)
delete(p);
parpool('local',nc);
else
if ~p.Connected||p.NumWorkers~=nc
delete(p);
parpool('local',nc);
end
end
nc=64; % Change number of chuncks (not workers) to avoid
% having too large arrays in memory on cores. Not sure
% if the problem is the size of Xr,Yr or Xchunck,Ychunck
p=gcp;
np=numel(X);
chunck=floor(np./nc);
NN=zeros(np,1); dNN=NN;
% NOTE! NN shouldn't be "single" since this can end up rounding up
% indices when they are passed to this array.
% Parallel loop.
NN_=cell(nc,1); dNN_=NN_;
parfor n=1:nc
if n==nc
these=((n-1)*chunck+1):np;
else
these=((n-1)*chunck+1):(n*chunck);
end
Xchunck=X(these); Xchunck=Xchunck(:);
Ychunck=Y(these); Ychunck=Ychunck(:);
[NN_{n},dNN_{n}]=knnsearch([Xr Yr],[Xchunck,Ychunck]);
end
% Allocate the output of the parallel loop to NN and dNN.
for n=1:nc
if n==nc
these=((n-1)*chunck+1):np;
else
these=((n-1)*chunck+1):(n*chunck);
end
NN(these)=NN_{n};
dNN(these)=dNN_{n};
end
else
% No parallel loop, just one call to knnsearch.
[NN,dNN]=knnsearch([Xr(:) Yr(:)],[X(:) Y(:)]);
end
ii=numel(y); jj=numel(x);
r=zeros(ii,jj,nb,'uint8');
for b=1:nb
temp=rr(:,b);
temp=temp(NN);
% Something strange with the next line for Sentinel-2 (works fine for the
% rest ?).
temp(dNN>sqrt(2).*delta+1)=0; % Ignore neighbors more than one pixel away.
r(:,:,b)=reshape(temp,ii,jj);
end
% Save the output.
t=zeros(ns,1); SE=t;
for s=1:ns
t(s)=rs(s).t;
SE(s)=rs(s).SE;
end
rout.r=r;
rout.sf=sf;
rout.x=x;
rout.y=y;
rout.t=mean(t);
rout.SE=mean(SE);
rout.delta=delta;
rout.utmz=rs(1).utmz;
rout.order=rs(1).order;
rout.source=rs(1).source;
%% Read functions for each satellite type.
%% PlanetScope
% PROBLEM reading .tif files that don't contain the string "_clip" for
% planet. Temporary fix: ignore these files. E.g. 23-Mar-2017 directory
% 3 is a problem.
function ris=r_PlanetScope(indir,aoi)
cont=dir(indir); % <-- Contents of the read directory
cont=cont(3:end);
if exist([indir '1'],'dir') % Multiple scenes.
ns=numel(cont);
else
ns=1;
end
sourcecell=cell(ns,1);
for s=1:ns
sourcecell{s}='PlanetScope';
end
ris=struct('source',sourcecell); % <-- Allocate the output structure.
% Loop over scenes.
for s=1:ns
% Define the read directory for the given scene.
if ns==1
readdir=indir;
else
readdir=[indir sprintf('%d/',s)];
end
filesare=dir(readdir);
filesare=filesare(3:end);
% Read in metadata for the given scene.
mis=filesare(3).name;
out=parseXML([readdir mis]);
utmz=out.Children(10).Children(2).Children(2).Children(2).Children(6).Children(6).Children(1).Data;
utmz=strsplit(utmz,'/'); utmz=utmz{2};
utmz=strsplit(utmz,' '); utmz=utmz{4};
SE=str2double(out.Children(6).Children(2).Children(8).Children(2).Children(8).Children.Data);
t=out.Children(6).Children(2).Children(8).Children(2).Children(14).Children.Data;
t=datenum([t(1:10) ' ' t(12:19)],'yyyy-mm-dd HH:MM:SS');
% Read in the images.
fis=filesare(2).name;
if strcmp(fis(end-7:end),'clip.tif') % <-- Temporary fix, ignore problematic images.
disp('clipped');
[temp,sr]=geotiffread([readdir fis]); % B, G, R, NIR
%size(temp)
rtemp=zeros(size(temp));
bands=[3; 2; 1; 4]; % Position of the bands in A in the R-G-B-NIR array R (see note at start of code).
sf=zeros(4,1);
for b=1:4
indis=12+2*(b-1); % For band=1:4 third child index goes 12:2:18
sf(b)=str2double(out.Children(10).Children(2).Children(indis).Children(10).Children(1).Data);
rtemp(:,:,bands(b))=double(temp(:,:,b)).*sf(b);
end
temp=rtemp; clear rtemp;
% Proc domain
delta=sr.CellExtentInWorldX;
x=((sr.XWorldLimits(1)+delta/2):delta:(sr.XWorldLimits(2)-delta/2))';
y=((sr.YWorldLimits(1)+delta/2):delta:(sr.YWorldLimits(2)-delta/2))';
y=flipud(y);
dx=delta; dy=delta;
ulx=x(1); uly=y(1);
% Define your aoi.
xn=min(aoi.x)-3.*dx; xm=max(aoi.x)+3.*dx;
yn=min(aoi.y)-3.*dy; ym=max(aoi.y)+3.*dy;
% Check utm zone.
utmz=str2double(utmz(1:2)); % UTM zone of scene
targetutmz=str2double(aoi.utmz(1:2));
if utmz~=targetutmz % If wrong utm zone.
disp('wrong utm zone');
% First define a padded AOI in the "wrong" utm zone to speed up the
% interpolation/utm zone conversion.
cutmstruct = defaultm('utm'); %<--- The "correct" utm zone structure.
cutmstruct.zone = aoi.utmz;
cutmstruct.geoid = wgs84Ellipsoid;
cutmstruct = defaultm(cutmstruct);
[Xd,Yd]=meshgrid(aoi.x,aoi.y);
[LATd,LONd]=minvtran(cutmstruct,Xd(:),Yd(:));
wutmstruct=defaultm('utm'); %<----The "wrong" utm zone structure.
wutmstruct.zone=sprintf('%d%s',utmz,aoi.utmz(end)); % Inherit the letter from the correct utm zone.
wutmstruct.geoid=wgs84Ellipsoid;
wutmstruct=defaultm(wutmstruct);
[Xdw,Ydw]=mfwdtran(wutmstruct,LATd,LONd);
padcut=3*dx;
xdlim=[min(Xdw)-padcut max(Xdw)+padcut];
ydlim=[min(Ydw)-padcut max(Ydw)+padcut];
thesex=x>=xdlim(1)&x<=xdlim(2);
thesey=y>=ydlim(1)&y<=ydlim(2);
% Crop
% First to the domain.
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
notmissing=all(temp>0,3);
% Then crop out all the junk (missing pixels) to minimize
% the image size.
xn=min(X(notmissing)); xm=max(X(notmissing));
yn=min(Y(notmissing)); ym=max(Y(notmissing));
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
% Now define the location of the centroids of the cut out pixels in the
% correct utm zone.
[LAT,LON]=minvtran(wutmstruct,X,Y);
[X,Y]=mfwdtran(cutmstruct,LAT,LON);
else
% Crop
% First to the domain.
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
% Then crop out all the junk (missing pixels) to minimize
% the image size.
notmissing=all(temp>0,3);
xn=min(X(notmissing)); xm=max(X(notmissing));
yn=min(Y(notmissing)); ym=max(Y(notmissing));
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
end
ii=size(X,1);
jj=size(X,2);
ris(s).X=X;
ris(s).Y=Y;
ris(s).r=zeros(ii,jj,4,'uint8'); % PlanetScope is in uint16 by default.
ris(s).sf=zeros(4,1);
% Save the image for the given band to the output structure
% along with a band dependent scale factor.
% to scale from uint8 compression to the measured
% reflectance.
for b=1:4
btemp=temp(:,:,b);
ris(s).sf(b)=max(btemp(:))/255;
ris(s).r(:,:,b)=uint8(btemp./ris(s).sf(b));
% Might need to consider a saturation value like for S2!
end
else % Just make images you want to ignore into a single pixel at "origin".
disp('not clipped, ignoring');
ris(s).r=zeros(1,1,4,'uint8');
ris(s).sf=zeros(4,1);
ris(s).X=0;
ris(s).Y=0;
ulx=0; uly=0; dx=3;
end
ris(s).t=t;
ris(s).order={'R'; 'G'; 'B'; 'NIR'};
ris(s).SE=SE;
ris(s).utmz=aoi.utmz;
ris(s).delta=dx;
ris(s).ulx=single(round(ulx)); % ULC identifiers for UNCROPPED scene.
ris(s).uly=single(round(uly));
end % <- End scene (s) loop.
end % <- End read RapidEye function.
%% RapidEye
function ris=r_RapidEye(indir,aoi)
cont=dir(indir); % <-- Contents of the read directory
cont=cont(3:end);
if exist([indir '1'],'dir') % Multiple scenes.
ns=numel(cont);
else
ns=1;
end
sourcecell=cell(ns,1);
for s=1:ns
sourcecell{s}='RapidEye';
end
ris=struct('source',sourcecell); % <-- Allocate the output structure.
% Exo-atmospheric irradiance for RapidEye radiance to reflectance
% conversion (B,G,R,RE,NIR)
EAI=[1997.8; 1863.5; 1560.4; 1395.0; 1124.4];
% Loop over scenes.
for s=1:ns
% Define the read directory for the given scene.
if ns==1
readdir=indir;
else
readdir=[indir sprintf('%d/',s)];
end
filesare=dir(readdir);
filesare=filesare(3:end);
% Read in metadata for the given scene.
mis=filesare(2).name;
out=parseXML([readdir mis]);
utmz=out.Children(10).Children(2).Children(2).Children(2).Children(8).Children(6).Children.Data;
utmz=strsplit(utmz,'/'); utmz=utmz{2};
utmz=strsplit(utmz,' '); utmz=utmz{4};
SE=str2double(out.Children(6).Children(2).Children(8).Children(2).Children(8).Children.Data);
t=out.Children(6).Children(2).Children(8).Children(2).Children(14).Children.Data;
t=datenum([t(1:10) ' ' t(12:19)],'yyyy-mm-dd HH:MM:SS');
% Read in the images.
fis=filesare(1).name;
[temp,sr]=geotiffread([readdir fis]);
rtemp=zeros(size(temp,1),size(temp,2),4);
bands=[3; 2; 1; NaN; 4]; % Position of the bands in temp in the R-G-B-NIR array R (see note at start of code).
sf=zeros(5,1);
year=datevec(t); year=year(1);
doy=floor(t)-datenum(sprintf('01-Jan-%d',year));
SunDist=1-0.01672.*cos(deg2rad(0.9856.*(doy-4))); % Estimate of earth sun distance (AU).
for b=1:5
if ~isnan(bands(b))
sf(b)=str2double(out.Children(10).Children(2).Children(12).Children(14).Children.Data);
rad_to_ref=pi.*SunDist.^2./(EAI(b).*cos(deg2rad(90-SE))); % See Planet labs product specification document.
rtemp(:,:,bands(b))=rad_to_ref.*double(temp(:,:,b)).*sf(b);
end
end
temp=rtemp;
clear r;
% Proc domain
delta=sr.CellExtentInWorldX;
x=((sr.XWorldLimits(1)+delta/2):delta:(sr.XWorldLimits(2)-delta/2))';
y=((sr.YWorldLimits(1)+delta/2):delta:(sr.YWorldLimits(2)-delta/2))';
y=flipud(y);
dx=delta; dy=delta;
ulx=x(1); uly=y(1);
% Define your aoi.
xn=min(aoi.x)-3.*dx; xm=max(aoi.x)+3.*dx;
yn=min(aoi.y)-3.*dy; ym=max(aoi.y)+3.*dy;
% Check utm zone.
utmz=str2double(utmz(1:2)); % UTM zone of scene
targetutmz=str2double(aoi.utmz(1:2));
if utmz~=targetutmz % If wrong utm zone.
disp('wrong utm zone');
% First define a padded AOI in the "wrong" utm zone to speed up the
% interpolation/utm zone conversion.
cutmstruct = defaultm('utm'); %<--- The "correct" utm zone structure.
cutmstruct.zone = aoi.utmz;
cutmstruct.geoid = wgs84Ellipsoid;
cutmstruct = defaultm(cutmstruct);
[Xd,Yd]=meshgrid(aoi.x,aoi.y);
[LATd,LONd]=minvtran(cutmstruct,Xd(:),Yd(:));
wutmstruct=defaultm('utm'); %<----The "wrong" utm zone structure.
wutmstruct.zone=sprintf('%d%s',utmz,aoi.utmz(end)); % Inherit the letter from the correct utm zone.
wutmstruct.geoid=wgs84Ellipsoid;
wutmstruct=defaultm(wutmstruct);
[Xdw,Ydw]=mfwdtran(wutmstruct,LATd,LONd);
padcut=3*dx;
xdlim=[min(Xdw)-padcut max(Xdw)+padcut];
ydlim=[min(Ydw)-padcut max(Ydw)+padcut];
thesex=x>=xdlim(1)&x<=xdlim(2);
thesey=y>=ydlim(1)&y<=ydlim(2);
% Crop
% First to the domain.
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
notmissing=all(temp>0,3);
% Then crop out all the junk (missing pixels) to minimize
% the image size.
xn=min(X(notmissing)); xm=max(X(notmissing));
yn=min(Y(notmissing)); ym=max(Y(notmissing));
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
% Now define the location of the centroids of the cut out pixels in the
% correct utm zone.
[LAT,LON]=minvtran(wutmstruct,X,Y);
[X,Y]=mfwdtran(cutmstruct,LAT,LON);
else
% Crop
% First to the domain.
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
% Then crop out all the junk (missing pixels) to minimize
% the image size.
notmissing=all(temp>0,3);
xn=min(X(notmissing)); xm=max(X(notmissing));
yn=min(Y(notmissing)); ym=max(Y(notmissing));
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
temp=temp(thesey,thesex,:);
end
ii=size(X,1);
jj=size(X,2);
ris(s).X=X;
ris(s).Y=Y;
ris(s).r=zeros(ii,jj,4,'uint8'); % Landsat 8 is in uint16 by default.
ris(s).sf=zeros(4,1);
% Save the image for the given band to the output structure
% along with a band dependent scale factor.
% to scale from uint8 compression to the measured
% reflectance.
for b=1:4
btemp=temp(:,:,b);
ris(s).sf(b)=max(btemp(:))/255;
ris(s).r(:,:,b)=uint8(btemp./ris(s).sf(b));
% Might need to consider a saturation value like for S2!
end
ris(s).t=t;
ris(s).order={'R'; 'G'; 'B'; 'NIR'};
ris(s).SE=SE;
ris(s).utmz=aoi.utmz;
ris(s).delta=dx;
ris(s).ulx=single(round(ulx)); % ULC identifiers for UNCROPPED scene.
ris(s).uly=single(round(uly));
end % <- End scene (s) loop.
end % <- End read RapidEye function.
%% Sentinel-2
function ris=r_Sentinel_2(indir,aoi)
cont=dir(indir); % <-- Contents of the read directory
cont=cont(3:end);
sfs2=1e4; % Sentinel-2 scale factor.
sats2=65535; % Saturated pixel value.
if exist([indir '1'],'dir') % Multiple scenes.
ns=numel(cont);
else
ns=1;
end
sourcecell=cell(ns,1);
for s=1:ns
sourcecell{s}='Sentinel-2';
end
ris=struct('source',sourcecell); % <-- Allocate the output structure.
% Loop over scenes.
for s=1:ns
% Define the read directory for the given scene.
if ns==1
readdir=indir;
else
readdir=[indir sprintf('%d/',s)];
end
filesare=dir(readdir);
filesare=filesare(3:end);
% Read in metadata for the given scene.
mis=filesare(end).name;
out=parseXML([readdir mis]);
these=out.Children(4).Children(2);
utmz=these.Children(2).Children.Data;
utmz=strsplit(utmz,' ');
utmz=utmz{end};
nr=str2double(these.Children(6).Children(2).Children.Data);
nc=str2double(these.Children(6).Children(4).Children.Data);
ulx=str2double(these.Children(12).Children(2).Children.Data);
uly=str2double(these.Children(12).Children(4).Children.Data);
dx=str2double(these.Children(12).Children(6).Children.Data);
dy=str2double(these.Children(12).Children(8).Children.Data);
x=(ulx+(dx.*(0:(nc-1))))';
y=(uly+(dy.*(0:(nr-1))))';
t=out.Children(2).Children(8).Children.Data;
t=datenum([t(1:10) ' ' t(12:19)]);
these=out.Children(4).Children(4).Children(4);
SE=90-str2double(these.Children(2).Children.Data);
% Loop over bands (files in the subdirectory)
for f=1:6
disp(sprintf('Sentinel-2 Band %d',f));
temp=single(imread([readdir filesare(f).name]));
if f==1
% Define your aoi.
xn=min(aoi.x)-3.*dx; xm=max(aoi.x)+3.*dx;
yn=min(aoi.y)-3.*dy; ym=max(aoi.y)+3.*dy;
% Check utm zone.
utmz=str2double(utmz(1:2)); % UTM zone of scene
targetutmz=str2double(aoi.utmz(1:2));
if utmz~=targetutmz % If wrong utm zone.
disp('wrong utm zone');
% First define a padded AOI in the "wrong" utm zone to speed up the
% interpolation/utm zone conversion.
cutmstruct = defaultm('utm'); %<--- The "correct" utm zone structure.
cutmstruct.zone = aoi.utmz;
cutmstruct.geoid = wgs84Ellipsoid;
cutmstruct = defaultm(cutmstruct);
[Xd,Yd]=meshgrid(aoi.x,aoi.y);
[LATd,LONd]=minvtran(cutmstruct,Xd(:),Yd(:));
wutmstruct=defaultm('utm'); %<----The "wrong" utm zone structure.
wutmstruct.zone=sprintf('%d%s',utmz,aoi.utmz(end)); % Inherit the letter from the correct utm zone.
wutmstruct.geoid=wgs84Ellipsoid;
wutmstruct=defaultm(wutmstruct);
[Xdw,Ydw]=mfwdtran(wutmstruct,LATd,LONd);
padcut=3*dx;
xdlim=[min(Xdw)-padcut max(Xdw)+padcut];
ydlim=[min(Ydw)-padcut max(Ydw)+padcut];
thesex=x>=xdlim(1)&x<=xdlim(2);
thesey=y>=ydlim(1)&y<=ydlim(2);
% Now define the location of the centroids of the cut out pixels in the
% correct utm zone.
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
[LAT,LON]=minvtran(wutmstruct,X,Y);
[X,Y]=mfwdtran(cutmstruct,LAT,LON);
else
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
end
ii=size(X,1);
jj=size(X,2);
ris(s).X=X;
ris(s).Y=Y;
ris(s).r=zeros(ii,jj,6,'uint8'); % Landsat 8 is in uint16 by default.
ris(s).sf=zeros(6,1);
end
% Save the image for the given band to the output structure
% along with a band dependent scale factor.
% to scale from uint8 compression to the measured
% reflectance.
if f<4
bis=4-f; % RGB
else
bis=f; % NIR, SWIR1, SWIR2
end
if f>4 % % Interpolate SWIR (20 m) to 10 m grid using NN.
temp=imresize(temp,[nr,nc],'nearest');
end
temp=temp(thesey,thesex); % Crop
temp(temp==sats2)=max(temp(temp~=sats2)); % Set saturated values to maximum reflectance.
scaled=double(temp)./sfs2;
scaled(scaled<0)=0;
ris(s).sf(bis)=max(scaled(:))./255;
ris(s).r(:,:,bis)=uint8(scaled./ris(s).sf(bis));
end % <- End band (f) loop.
ris(s).t=t;
ris(s).order={'R'; 'G'; 'B'; 'NIR'; 'SWIR1'; 'SWIR2'};
ris(s).SE=SE;
ris(s).utmz=aoi.utmz;
ris(s).delta=dx;
ris(s).ulx=single(round(ulx)); % ULC identifiers for UNCROPPED scene.
ris(s).uly=single(round(uly));
end % <- End scene (s) loop.
end % <- End read Sentinel-2 function.
%% Landsat 7
function ris=r_Landsat_7(indir,aoi)
cont=dir(indir); % <-- Contents of the read directory
cont=cont(3:end);
% Search strings in the Landsat 7 metadata.
searchstr=cell(16,1); searchval=zeros(size(searchstr));
for str=1:numel(searchstr)
if str==1
searchstr{str}='DATE_ACQUIRED';
elseif str==2
searchstr{str}='SCENE_CENTER_TIME';
elseif str==3
searchstr{str}='SUN_ELEVATION';
elseif str<=9
b=str-3; % Bands 1-5&7
b=b.*(b~=6)+7.*(b==6);
searchstr{str}=sprintf('REFLECTANCE_MULT_BAND_%d',b);
elseif str<=15
b=str-9; % Bands 1-5&7
b=b.*(b~=6)+7.*(b==6);
searchstr{str}=sprintf('REFLECTANCE_ADD_BAND_%d',b);
else
searchstr{str}='UTM_ZONE';
end
end
if exist([indir '1'],'dir') % Multiple scenes.
ns=numel(cont);
else
ns=1;
end
sourcecell=cell(ns,1);
for s=1:ns
sourcecell{s}='Landsat 7';
end
ris=struct('source',sourcecell); % <-- Allocate the output structure.
% Loop over scenes.
for s=1:ns
% Define the read directory for the given scene.
if ns==1
readdir=indir;
else
readdir=[indir sprintf('%d/',s)];
end
filesare=dir(readdir);
filesare=filesare(3:end);
% Read in metadata for the given scene.
mis=[readdir filesare(end).name];
fid=fopen(mis);
t=[];
str=1;
while str<=numel(searchstr)
line=fgetl(fid);
lines=strsplit(line,'=');
if any(strcmp(searchstr{str},strtrim(lines{1})))
if str<=2
t=[t lines{end}];
if str==2
t=datenum([t(1:11) ' ' t(14:21)],'yyyy-mm-dd HH:MM:SS');
end
else
searchval(str)=str2double(lines{end});
end
str=str+1;
end
end
% Loop over bands
for f=1:6
disp(sprintf('Landsat 7 Band %d',f));
[temp,sr]=geotiffread([readdir filesare(f).name]);
% Retrieve georeferencing information for first band (same for
% all).
if f==1
dx=sr.SampleSpacingInWorldX;
dy=sr.SampleSpacingInWorldY;
nr=sr.RasterSize(1);
nc=sr.RasterSize(2);
ulx=sr.XWorldLimits(1);
uly=sr.YWorldLimits(1);
x=single((ulx+(dx.*(0:(nc-1))))');
y=single(flipud((uly+(dy.*(0:(nr-1))))'));
% Define your aoi.
xn=min(aoi.x)-3.*dx; xm=max(aoi.x)+3.*dx;
yn=min(aoi.y)-3.*dy; ym=max(aoi.y)+3.*dy;
utmz=searchval(end); % UTM zone of scene
targetutmz=str2double(aoi.utmz(1:2));
if utmz~=targetutmz % If wrong utm zone.
disp('wrong utm zone');
% First define a padded AOI in the "wrong" utm zone to speed up the
% interpolation/utm zone conversion.
cutmstruct = defaultm('utm'); %<--- The "correct" utm zone structure.
cutmstruct.zone = aoi.utmz;
cutmstruct.geoid = wgs84Ellipsoid;
cutmstruct = defaultm(cutmstruct);
[Xd,Yd]=meshgrid(aoi.x,aoi.y);
[LATd,LONd]=minvtran(cutmstruct,Xd(:),Yd(:));
wutmstruct=defaultm('utm'); %<----The "wrong" utm zone structure.
wutmstruct.zone=sprintf('%d%s',utmz,aoi.utmz(end)); % Inherit the letter from the correct utm zone.
wutmstruct.geoid=wgs84Ellipsoid;
wutmstruct=defaultm(wutmstruct);
[Xdw,Ydw]=mfwdtran(wutmstruct,LATd,LONd);
padcut=3*dx;
xdlim=[min(Xdw)-padcut max(Xdw)+padcut];
ydlim=[min(Ydw)-padcut max(Ydw)+padcut];
thesex=x>=xdlim(1)&x<=xdlim(2);
thesey=y>=ydlim(1)&y<=ydlim(2);
% Now define the location of the centroids of the cut out pixels in the
% correct utm zone.
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
[LAT,LON]=minvtran(wutmstruct,X,Y);
[X,Y]=mfwdtran(cutmstruct,LAT,LON);
else
thesex=x>=xn&x<=xm;
thesey=y>=yn&y<=ym;
x=x(thesex); y=y(thesey);
[X,Y]=meshgrid(x,y);
end
nr=size(X,1);
nc=size(X,2);
ris(s).X=X;
ris(s).Y=Y;
ris(s).r=zeros(nr,nc,6,'uint8'); % Landsat 8 is in uint16 by default.
ris(s).sf=zeros(6,1);
end
% Save the image for the given band to the output structure
% along with a band dependent scale factor.
% to scale from uint16 compression to the measured
% reflectance.
if f<4
bis=4-f; % RGB
else
bis=f; % NIR, SWIR1, SWIR2
end
scaled=(searchval(3+f).*double(temp(thesey,thesex))+searchval(9+f))./sin(deg2rad(searchval(3)));
scaled(scaled<0)=0;
ris(s).sf(bis)=max(scaled(:))./255;
ris(s).r(:,:,bis)=uint8(scaled./ris(s).sf(bis));
end % <- End band (f) loop.
ris(s).t=t;
ris(s).order={'R'; 'G'; 'B'; 'NIR'; 'SWIR1'; 'SWIR2'};
ris(s).SE=searchval(3);
ris(s).utmz=aoi.utmz;
ris(s).delta=dx;
ris(s).ulx=single(round(ulx)); % ULC identifiers for UNCROPPED scene.
ris(s).uly=single(round(uly));
end % <- End scene (s) loop.
end % <- End read Landsat_7 function.
%% Landsat 8
function ris=r_Landsat_8(indir,aoi)
cont=dir(indir); % <-- Contents of the read directory
cont=cont(3:end);
% Search strings in the Landsat 8 metadata.
searchstr=cell(16,1); searchval=zeros(size(searchstr));
for str=1:numel(searchstr)
if str==1
searchstr{str}='DATE_ACQUIRED';
elseif str==2
searchstr{str}='SCENE_CENTER_TIME';
elseif str==3
searchstr{str}='SUN_ELEVATION';
elseif str<=9 % Bands 2,3,4,5,6,7
searchstr{str}=sprintf('REFLECTANCE_MULT_BAND_%d',str-2);
elseif str<=15 % Bands 2,3,4,5,6,7
searchstr{str}=sprintf('REFLECTANCE_ADD_BAND_%d',str-8);
else
searchstr{str}='UTM_ZONE';
end
end
if exist([indir '1'],'dir') % Multiple scenes.
ns=numel(cont);
else
ns=1;
end
sourcecell=cell(ns,1);
for s=1:ns
sourcecell{s}='Landsat 8';
end
ris=struct('source',sourcecell); % <-- Allocate the output structure.
% Loop over scenes.
for s=1:ns
% Define the read directory for the given scene.
if ns==1
readdir=indir;
else
readdir=[indir sprintf('%d/',s)];
end
filesare=dir(readdir);
filesare=filesare(3:end);
% Read in metadata for the given scene.
mis=[readdir filesare(end).name];
fid=fopen(mis);
t=[];
str=1;
while str<=numel(searchstr)
line=fgetl(fid);
lines=strsplit(line,'=');
if any(strcmp(searchstr{str},strtrim(lines{1})))
if str<=2