-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlandsat_cloudScore.py
269 lines (194 loc) · 13 KB
/
landsat_cloudScore.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
# Sentinel-2 package
from paramsTemplate import *
import ee
from Py6S import *
import math
import datetime
import os, sys
from utils import *
import sun_angles
import view_angles
import time
class env(object):
def __init__(self):
"""Initialize the environment."""
# Initialize the Earth Engine object, using the authentication credentials.
ee.Initialize()
self.epsg = "EPSG:32717"
##########################################
# variable for the landsat data request #
##########################################
self.metadataCloudCoverMax = 100;
##########################################
# Export variables #
##########################################
self.assetId ="projects/Sacha/PreprocessedData/L8_Annual_CloudScore/"
self.name = "LS_CS_"
self.exportScale = 20
self.cloudScoreThresh = 1;
##########################################
# variable band selection #
##########################################
self.percentiles = [25,75]
self.divideBands = ee.List(['blue','green','red','nir','swir1','swir2'])
self.bandNamesLandsat = ee.List(['blue','green','red','nir','swir1','thermal','swir2','sr_atmos_opacity','pixel_qa','radsat_qa'])
self.sensorBandDictLandsatSR = ee.Dictionary({'L8' : ee.List([1,2,3,4,5,7,6,9,10,11]),\
'L7' : ee.List([0,1,2,3,4,5,6,7,9,10]),\
'L5' : ee.List([0,1,2,3,4,5,6,7,9,10]),\
'L4' : ee.List([0,1,2,3,4,5,6,7,9,10])})
##########################################
# enable / disable modules #
##########################################
self.cloudMask = True
class functions():
def __init__(self):
"""Initialize the Surfrace Reflectance app."""
# get the environment
self.env = env()
def main(self,studyArea,startDate,endDate,startDay,endDay,week,regionName):
self.env.startDate = startDate
self.env.endDate = endDate
self.env.startDoy = startDay
self.env.endDoy = endDay
self.env.regionName = regionName
self.studyArea = studyArea
landsat8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR').filterDate(self.env.startDate,self.env.endDate).filterBounds(studyArea)
landsat8 = landsat8.filterMetadata('CLOUD_COVER','less_than',self.env.metadataCloudCoverMax)
landsat8 = landsat8.select(self.env.sensorBandDictLandsatSR.get('L8'),self.env.bandNamesLandsat)
landsat5 = ee.ImageCollection('LANDSAT/LT05/C01/T1_SR').filterDate(self.env.startDate,self.env.endDate).filterBounds(studyArea)
landsat5 = landsat5.filterMetadata('CLOUD_COVER','less_than',self.env.metadataCloudCoverMax)
landsat5 = landsat5.select(self.env.sensorBandDictLandsatSR.get('L5'),self.env.bandNamesLandsat).map(self.defringe)
landsat7 = ee.ImageCollection('LANDSAT/LE07/C01/T1_SR').filterDate(self.env.startDate,self.env.endDate).filterBounds(studyArea)
landsat7 = landsat7.filterMetadata('CLOUD_COVER','less_than',self.env.metadataCloudCoverMax)
landsat7 = landsat7.select(self.env.sensorBandDictLandsatSR.get('L7'),self.env.bandNamesLandsat)
landsat = landsat5.merge(landsat7).merge(landsat8)
if landsat.size().getInfo() > 0:
landsat = landsat.map(self.scaleLandsat)
# mask clouds using cloud mask function
if self.env.cloudMask == True:
#print "removing some more clouds"
landsat = landsat.map(self.maskClouds)
landsat = landsat.select(['cloudScore','pixel_qa'])
landsat = self.percentile(landsat,self.env.percentiles)
landsat = landsat.set('system:time_start',ee.Date(self.env.startDate).millis())
self.exportMap(landsat,studyArea,week)
print(landsat.getInfo())
return landsat
def scaleLandsat(self,img):
"""Landast is scaled by factor 0.0001 """
thermal = img.select(ee.List(['thermal'])).multiply(0.1)
scaled = ee.Image(img).select(self.env.divideBands).multiply(ee.Number(0.0001))
return img.select(['pixel_qa']).addBands(scaled).addBands(thermal)
def maskClouds(self,img):
"""
Computes spectral indices of cloudyness and take the minimum of them.
Each spectral index is fairly lenient because the group minimum
is a somewhat stringent comparison policy. side note -> this seems like a job for machine learning :)
originally written by Matt Hancher for Landsat imageryadapted to Sentinel by Chris Hewig and Ian Housman
"""
score = ee.Image(1.0);
# Clouds are reasonably bright in the blue band.
blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide(ee.Number(0.3).subtract(ee.Number(0.1)))
score = score.min(blue_rescale);
# Clouds are reasonably bright in all visible bands.
visible = img.select('red').add(img.select('green')).add(img.select('blue'))
visible_rescale = visible.subtract(ee.Number(0.2)).divide(ee.Number(0.8).subtract(ee.Number(0.2)))
score = score.min(visible_rescale);
# Clouds are reasonably bright in all infrared bands.
infrared = img.select('nir').add(img.select('swir1')).add(img.select('swir2'))
infrared_rescale = infrared.subtract(ee.Number(0.3)).divide(ee.Number(0.8).subtract(ee.Number(0.3)))
score = score.min(infrared_rescale);
# Clouds are reasonably cool in temperature.
temp_rescale = img.select('thermal').subtract(ee.Number(300)).divide(ee.Number(290).subtract(ee.Number(300)))
score = score.min(temp_rescale);
# However, clouds are not snow.
ndsi = img.normalizedDifference(['green', 'swir1']);
ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide(ee.Number(0.6).subtract(ee.Number(0.8)))
score = score.min(ndsi_rescale).multiply(100).byte().rename(['cloudScore']);
mask = score.lt(self.env.cloudScoreThresh).rename(['cloudMask']);
img = img.updateMask(mask).addBands([mask]).addBands([score]);
return img;
def defringe(self,img):
# threshold for defringing landsat5 and 7
fringeCountThreshold = 279
k = ee.Kernel.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er.min())
sum = m.reduceNeighborhood(ee.Reducer.sum(), k, 'kernel')
mask = sum.gte(fringeCountThreshold)
return img.updateMask(mask)
def percentile(self,collection,p):
median = ee.ImageCollection(collection).reduce(ee.Reducer.median()).rename(['cloudScore','pixel_qa']);
percentiles = collection.reduce(ee.Reducer.percentile(p))
return median.addBands(percentiles)
def exportMap(self,img,studyArea,week):
geom = studyArea.getInfo();
sd = str(self.env.startDate.getRelative('day','year').getInfo()).zfill(3);
ed = str(self.env.endDate.getRelative('day','year').getInfo()).zfill(3);
year = str(self.env.startDate.get('year').getInfo());
regionName = self.env.regionName.replace(" ",'_') + "_"
task_ordered= ee.batch.Export.image.toAsset(image=img,
description = self.env.name + regionName + str(week).zfill(3) +'_'+ year + sd + ed,
assetId= self.env.assetId + self.env.name + regionName + str(week).zfill(3)+'_'+ year + sd + ed,
region=geom['coordinates'],
maxPixels=1e13,
crs=self.env.epsg,
scale=self.env.exportScale)
task_ordered.start()
print(self.env.assetId + self.env.name + regionName + str(week).zfill(3)+'_'+ year + sd + ed)
if __name__ == "__main__":
ee.Initialize()
start = 0
for i in range(0,2,1):
#2018 starts at week 104
runNumber = start+ i
print runNumber
year = ee.Date("2009-01-01")
startDay = 0
endDay = 364
startDate = year.advance(startDay,'day').advance(i,'year')
endDate = year.advance(endDay,'day').advance(i,'year')
regionName = 'ECUADOR'
studyArea = ee.FeatureCollection("projects/Sacha/AncillaryData/StudyRegions/Ecuador_EcoRegions_Complete")
studyArea = studyArea.geometry().bounds()
functions().main(studyArea,startDate,endDate,startDay,endDay,runNumber,regionName)