Skip to content
Extraits de code Groupes Projets
Valider abb4255b rédigé par Dries De Bièvre's avatar Dries De Bièvre
Parcourir les fichiers

landsat script

parent 1ac9418d
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
%% Cell type:markdown id:646198a0-e6d2-4145-bddc-69e97623fdfc tags:
# Load Landsat Collection
Landsat, a joint program of the USGS and NASA, has been observing the Earth continuously from 1972 through the present day. Today the Landsat satellites image the entire Earth's surface at a 30-meter resolution about once every two weeks, including multispectral and thermal data.
Landsat data is available in Earth Engine in its raw form, as Surface Reflectance, TOA-corrected reflectance, and in various ready-to-use computed products such as NDVI and EVI vegetation indices.
> **📝 Note:**
>In this course we will only work with *Landsat Collection 2* that marks the second major reprocessing effort on the Landsat archive by the USGS that results in several data product improvements over Collection 1 that harness recent advancements in data processing and algorithm development.
|Satellite | Landsat 5 | Landsat 7 | Landsat 8 | Landsat 9 |
|----------|:----------: |:----------:|:---------: | :--------:|
|**Instrument** | <font size="2"> Multispectral Scanner (MSS), <br/>Thematic Mapper (TM) </font>| <font size="2"> Enhanced Thematic Mapper <br/> (ETM+) </font>| <font size="2"> Operational Land Imager (OLI),<br/> Thermal Infrared <br/>Sensor (TIRS)</font>| <font size="2"> OLI-2, TIRS-2 </font>|
|**Number of bands**| 10 | 10 | 10 | 10 |
|**Spatial resolution**| 30m x 30m | 30m x 30m| 30m x 30m | 30m x 30m
|**Temporal resolution**| 16 days | 16 days | 16 days | 16 days
|**Temporal range**| 1984 - 2012 |1999 - Present| 2013 - Present | 2021 - Present
|**Google Earth Engine collection** | [Dataset](https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LT05_C02_T1_L2) | [Dataset](https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LE07_C02_T1_L2) | [Dataset](https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C02_T1_L2)| [Dataset](https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2?hl=en) |
Let's define which datasets we will work with.
```js
// Load USGS Landsat 5 Level 2, Collection 2, Tier 1
var landsat_5 = ee.ImageCollection("LANDSAT/LT05/C02/T1_L2")
// Load USGS Landsat 7 Level 2, Collection 2, Tier 1
var landsat_7 = ee.ImageCollection("LANDSAT/LE07/C02/T1_L2")
// Load USGS Landsat 8 Level 2, Collection 2, Tier 1
var landsat_8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
// Load USGS Landsat 9 Level 2, Collection 2, Tier 1
var landsat_9 = ee.ImageCollection('LANDSAT/LC09/C02/T1_L2')
```
## Filter Landsat data
```js
// Define time period
var startDate = '2024-01-01'
var endDate = '2024-12-31'
```
```js
var fao_level1 = ee.FeatureCollection("FAO/GAUL/2015/level1")
var roi = fao_level1.filter("ADM1_CODE == 602")
```
```js
// Select Landsat 8 images in area of interest and time period
var l8_filter = landsat_8
.filterDate(startDate, endDate)
.filterBounds(roi)
var l9_filter = landsat_9
.filterDate(startDate, endDate)
.filterBounds(roi)
```
## Apply scaling factors
A scale factor must be applied to both Collection 1 and Collection 2 Landsat Level-2 surface reflectance and surface temperature products before using the data.
**Landsat Collection 2** have the following scale factors, fill values, data type, and valid range.
<figure class="responsive-figure-table"><table>
<thead>
<tr>
<th>Science Product</th>
<th>Scale Factor</th>
<th>Fill Value</th>
<th>Data Type</th>
<th>Valid Range</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://www.usgs.gov/core-science-systems/nli/landsat/landsat-collection-2-surface-reflectance">Surface Reflectance</a></td>
<td>0.0000275 + -0.2</td>
<td>0</td>
<td>Unsigned 16-bit integer</td>
<td>1-65455</td>
</tr>
<tr>
<td><a href="https://www.usgs.gov/core-science-systems/nli/landsat/landsat-collection-2-surface-temperature">Surface Temperature</a></td>
<td>0.00341802 + 149.0</td>
<td>0</td>
<td>Unsigned 16-bit integer</td>
<td>1-65455</td>
</tr>
</tbody>
</table></figure>
> **📝 Note:**
> **Examples for scaling Landsat Collection 2 Level-2 science products**
> <font size="2">Landsat Collection 2 surface reflectance has a scale factor of 0.0000275 and an additional offset of -0.2 per pixel. <br/> For example, a pixel value of 18,639 is multiplied by 0.0000275 for the scale factor and then -0.2 is added for the additional offset to get a reflectance value of 0.313 after the scale factor is applied. </font>
```js
// Applies scaling factors.
function applyScaleFactors(image) {
var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2)
var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0)
return image.addBands(opticalBands, null, true)
.addBands(thermalBands, null, true)
}
var l8_filter = l8_filter.map(applyScaleFactors)
var l9_filter = l9_filter.map(applyScaleFactors)
```
%% Cell type:markdown id:a46e022f-ca87-42e0-a88c-b5ba0fd5c686 tags:
# Cloud Mask
Most optical satellite imagery products come with one or more QA-bands that allows the user to assess quality of each pixel and extract pixels that meet their requirements. The most common application for QA-bands is to extract information about cloudy pixels and mask them. But the QA bands contain a wealth of other information that can help you remove low quality data from your analysis. Typically the information contained in QA bands is stored as Bitwise Flags. [More info about bitmasks](https://spatialthoughts.com/2021/08/19/qa-bands-bitmasks-gee/)
In Landsat imagery, pixel quality assessment (QA_PIXEL) bands are generated by the CFMask algorithm. Different bit definitions are used because the cirrus band is only available on Landsat 8 and 9. This band is relevant to both Surface Reflectance and Surface Temperature products.
|Bit | Landat 5 & 7 |Landsat 8 & 9 |
|---------|:----------: |:----------:|
|0 | Fill | Fill |
|1 | Dilated Cloud|Dilated Cloud|
|2|Unused|Cirrus|
|3|Cloud|Cloud|
|4|Cloud Shadow|Cloud Shadow|
|5|Snow|Snow|
|6|Clear|Clear|
|7|Water|Water|
|8-9|Cloud Confidence|Cloud Confidence|
|10-11|Cloud Shadow Confidence|Cloud Shadow Confidence|
|12-13|Snow/Ice Confidence|Snow/Ice Confidence|
|14-15|Unused|Cirrus Confidence|
The two following functions will be used to mask clouds, cloud shadows, ... on every images of an `ImageCollection`.
```js
/**
* Utility to extract bitmask values.
* Look up the bit-ranges in the catalog.
*
* value - ee.Number or ee.Image to extract from.
* fromBit - int or ee.Number with the first bit.
* toBit - int or ee.Number with the last bit (inclusive).
* Defaults to fromBit.
*/
function bitwiseExtract(value, fromBit, toBit) {
if (toBit === undefined) toBit = fromBit
var maskSize = ee.Number(1).add(toBit).subtract(fromBit)
var mask = ee.Number(1).leftShift(maskSize).subtract(1)
return value.rightShift(fromBit).bitwiseAnd(mask)
}
```
```js
var maskClouds = function(image) {
var QA = image.select('QA_PIXEL');
var clouds = bitwiseExtract(QA, 3).eq(0)
var cloud_shadows = bitwiseExtract(QA, 4).eq(0)
var mask = clouds
.and(cloud_shadows)
var maskedImage = image.updateMask(mask)
return maskedImage
}
%% Cell type:markdown id:7b4b6830-5c8f-40aa-bbe3-6df939b0e508 tags:
# Composite
%% Cell type:markdown id:1277af19-5c90-4097-bc5d-9f26a373d767 tags:
```js
var l8_composite = l8_filter
.filterDate(startPeriod, endPeriod)
.map(maskClouds)
.median()
.clip(roi)
var l9_composite = l9_filter
.filterDate(startPeriod, endPeriod)
.map(maskClouds)
.median()
.clip(roi)
%% Cell type:markdown id:54832050-d981-46b3-be07-b0e8ac8e6695 tags:
# Visualization
%% Cell type:markdown id:9af7754e-1a0d-4146-9946-f17ba1d382ef tags:
```js
var visParams = {
bands: ['SR_B4', 'SR_B3', 'SR_B2'],
min: 0.0,
max: 0.3,
}
Map.centerObject(roi, 8)
Map.addLayer(l8_composite, visParams, 'True Color (432) - Mask - Median - Landsat 8')
Map.addLayer(l9_composite, visParams, 'True Color (432) - Mask - Median - Landsat 9')
%% Cell type:markdown id:a2daac93-fe02-4fb1-8781-3397bf403d52 tags:
```js
// Get projection of the original image
var projection = l8_filter.first().projection().getInfo()
// Export the image, specifying the CRS, transform, and region.
Export.image.toDrive({
image: l8_composite,
description: 'L8_2019_median_composite',
folder: 'LBRAT2104',
crs: projection.crs, // The base coordinate reference system of this projection (e.g. 'EPSG:4326')
crsTransform: projection.transform, // The transform between projected coordinates and the base coordinate system
region: roi
});
```
%% Cell type:code id:35281a8f-932f-48af-8b0c-db62a4639b0c tags:
``` python
```
%% Cell type:markdown id:7aee23a0-e716-4370-b590-307f2a6351a4 tags:
# Load Sentinel-2 Surface Reflectance
The Sentinel-2 L2 data are downloaded from the Copernicus DataSpace. They were computed by running Sen2Cor.
All information concerning *Harmonized Sentinel-2 MSI: MultiSpectral Instrument, Level-2A* are available [here](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR_HARMONIZED#description)
```js
// Load Harmonized Sentinel-2 MSI: MultiSpectral Instrument, Level-2A
var s2_sr = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
```
```{note}
The Sentinel Level-1C and Level-2A data products have a harmonized time series. The "harmonized" designation means that the band-dependent offset added to reflectance bands in the 04.00 processing baseline has been removed. The offset affects data after January 24th 2022; removing the offset puts these data in spectral alignment with pre-04.00 baseline data. If you are using COPERNICUS/S2 or COPERNICUS/S2_SR, it is recommended that you switch to COPERNICUS/S2_HARMONIZED and COPERNICUS/S2_SR_HARMONIZED.
```
> **📝 Note:**
>The Sentinel Level-1C and Level-2A data products have a harmonized time series. The "harmonized" designation means that the band-dependent offset added to reflectance bands in the 04.00 processing baseline has been removed. The offset affects data after January 24th 2022; removing the offset puts these data in spectral alignment with pre-04.00 baseline data. If you are using COPERNICUS/S2 or COPERNICUS/S2_SR, it is recommended that you switch to COPERNICUS/S2_HARMONIZED and COPERNICUS/S2_SR_HARMONIZED.
## Filter Sentinel-2 data
```js
// Define time period
var startDate = '2019-01-01'
var endDate = '2019-12-31'
```
```js
var fao_level1 = ee.FeatureCollection("FAO/GAUL/2015/level1")
var roi = fao_level1.filter("ADM1_CODE == 602")
```
```js
// Select S2 SR images in area of interest and time period
var s2_filter = s2_sr
.filterDate(startDate, endDate)
.filterBounds(roi)
// Pre-filter to get less cloudy granules.
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
```
%% Cell type:markdown id:51797ab3-9d2e-42b5-8315-c8c07dce9d27 tags:
# Cloud Mask
<p>Clouds can be removed by using the Sentinel-2 QA band
or the <a href="/earth-engine/datasets/catalog/COPERNICUS_S2_CLOUD_PROBABILITY">COPERNICUS/S2_CLOUD_PROBABILITY</a>.
## Mask clouds using the Sentinel-2 QA band
<section class="expandable">
<p class="showalways">Bitmask for QA60</p>
<ul>
<li> Bits 0-9: Unused
<ul>
</ul>
</li>
<li> Bit 10: Opaque clouds
<ul>
<li>0: No opaque clouds</li>
<li>1: Opaque clouds present</li>
</ul>
</li>
<li> Bit 11: Cirrus clouds
<ul>
<li>0: No cirrus clouds</li>
<li>1: Cirrus clouds present</li>
</ul>
</li>
</ul>
</section>
[More info](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR_HARMONIZED#bands)
```js
function maskS2cloudsQA(image) {
var qa = image.select('QA60')
// Bits 10 and 11 are clouds and cirrus, respectively.
var cloudBitMask = 1 << 10
var cirrusBitMask = 1 << 11
// Both flags should be set to zero, indicating clear conditions.
var cloud = qa.bitwiseAnd(cloudBitMask).eq(0)
var cirrus = qa.bitwiseAnd(cirrusBitMask).eq(0)
var mask = cloud
.and(cirrus)
var maskedImage = image.updateMask(mask).divide(10000);
return maskedImage
}
```
```js
var s2_mask_cloudsQA = s2_filter
.map(maskS2cloudsQA)
```
%% Cell type:markdown id:6f4134ce-a583-47b7-9580-555938ac0c74 tags:
# Composite
Reducers are the way to aggregate data over time, space, bands, arrays and other data structures in Earth Engine. The `ee.Reducer` class specifies how data is aggregated. The reducers in this class can specify a simple statistic to use for the aggregation (e.g. minimum, maximum, mean, median, standard deviation, etc.), or a more complex summary of the input data (e.g. histogram, linear regression, list).
Reductions may occur over :
- **time (`imageCollection.reduce()`),**
- space (`image.reduceRegion()`, `image.reduceNeighborhood()`),
- bands (`image.reduce()`),
- attribute space of a `FeatureCollection`** (`featureCollection.reduceColumns()` or `FeatureCollection` methods that start with `aggregate_`).
Consider the example of needing to take the median over a time series of images represented by an `ImageCollection`. To reduce an `ImageCollection`, use `imageCollection.reduce()`. This reduces the collection of images to an individual image. Specifically, the output is computed pixel-wise, such that each pixel in the output is composed of the median value of all the images in the collection at that location. To get other statistics, such as mean, sum, variance, an arbitrary percentile, etc., the appropriate reducer should be selected and applied.
```{note}
For basic statistics like min, max, mean, etc., `ImageCollection` has shortcut methods like `min()`, `max()`, `mean()`, etc. They function in exactly the same way as calling `reduce()`, except the resultant band names will not have the name of the reducer appended.
```
**To composite images in an `ImageCollection`, use `imageCollection.reduce()`. This will composite all the images in the collection to a single image representing, for example, the min, max, mean or standard deviation of the images.**
![reducer](Reduce_ImageCollection.png)
```js
var s2_composite_cloudsQA = s2_mask_cloudsQA
.median()
.clip(roi)
```
## Visualization
```js
var visParams = {
bands: ['B4','B3','B2'],
min: 0.0,
max: 0.3,
};
```
```js
Map.centerObject(roi, 8)
Map.addLayer(s2_composite_cloudsQA, visParams, 'S2 SR masked QA60')
```
## Exportation to Google Drive
```js
// Get projection of the original image
var projection = s2_filter.first().projection().getInfo()
// Export the image, specifying the CRS, transform, and region.
Export.image.toDrive({
image: s2_composite_cloudsQA,
description: 'S2_2025_median_composite',
folder: 'LBRAT2104',
crs: projection.crs, // The base coordinate reference system of this projection (e.g. 'EPSG:4326')
crsTransform: projection.transform, // The transform between projected coordinates and the base coordinate system
region: roi
});
```
> Composite images created by reducing an image collection are able to produce pixels in any requested projection and therefore have no fixed output projection. Instead, composites have the default projection of WGS-84 with 1-degree resolution pixels. Composites with the default projection will be computed in whatever output projection is requested. A request occurs by displaying the composite in the Code Editor or by explicitly specifying a projection/scale as in an aggregation such as `ReduceRegion` or `Export`.
%% Cell type:code id:646300ef-0748-41d7-9a19-1b506e0616c0 tags:
``` python
```
......
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter