- Resample 20m spatial resolutions bands to 10m (if you want to work with 20m bands)
- Cropping images to the extent of Region of Interest (ROI)
- Apply Scene Classification map (SCL) on reflectance images to mask invalid pixels
- Calculate the fraction of valid pixels in your ROI
If your ROI spans several S2 tiles, start by preprocessing each tile one by one using this notebook and then use the "Mosaic Sentinel-2 tiles" notebook to mosaic the entire ROI.
print(f'{len(list_L2A)} L2A will be pre-processed \n')
for L2A_safe in list_L2A:
L2A_name = os.path.basename(L2A_safe)
print(L2A_name)
```
%% Cell type:markdown id: tags:
## 1. Resample images at 20m resolution to 10m
| Methods | Type of data | How it works |
|:---------:|:----------:| ---- |
| Nearest Neighbor | categorical| <font size="2">The value of of the output cell is determined by the nearest cell center on the input grid </font>|
| Bilinear Interpolation | continuous | <font size="2"> Weighted average of the four nearest cell centers. <br/> The closer an input cell center is to the output cell center, the higher the influence of its value is on the output cell value. The output value could be different than the nearest input but is always within the same range of values as the input. </font>|
| Cubic Convolution | continuous | <font size="2">Looks at the 16 nearest cell centers to the output and fits a smooth curve through the points to find the value. <br/>Not only does this change the values of the input but it could also cause the output value to be outside of the range of input values (imagine a sink or a peak occurring on a surface). </font> |
### 1.1 Resample Scene Classification map
> **WARNING**: Only if you are planning to work at 10m resolution. If you are planning to work at 20m resolution, you can skip this step!
If you work only with Blue (B02), Green (B03), Red (B04) and NIR (B08) bands, you don't have to do the resampling step because theses reflectances are already available at 10m resolution.
This step is only necessary if you work with bands 5,6,7,8A,11,12 which are only available at 20m resolution.
## 2. Clip images to the extent of Region of Interest
We can use our ROI (vector) to clip satellite images (raster) into a smaller area to reduce image storage and speed up further processing.
%% Cell type:markdown id: tags:
Get list of all images to clip
> **WARNING**: All images must be at same spatial resolution !
%% Cell type:markdown id: tags:
<div class="alert alert-warning">
<h4 class="alert-heading"><strong>Second exercise of the session</strong></h4>
<hr>
### Exercise: Find All 10m Resolution Images for Clipping
Your task is to use the `glob` module to create a list of **all 10m resolution images** from both the **resampled folder** and the **original downloaded SAFE files**.
The list should be stored in the `list_im_to_clip` variable.
#### Steps:
1. Use `glob.glob()` to find all `*_10m.tif` images in your **resampled folder**.
2. Loop through each band in `band_10m_list` and use `glob.glob()` to find `*_10m.jp2` images in the **original `.SAFE` directories**.
3. Append the found images to `list_im_to_clip`.
4. Print the total number of images found.
**Hint 1:**
- Your **resampled images** are in `"X:/STUDENTS/GROUP_{your group number}/RESAMPLED/"`.
- Your **original images** are in `"X:/STUDENTS/GROUP_{your group number}/DOWNLOAD/*.SAFE/GRANULE/*/IMG_DATA/R10m/"`.
**Hint 2:**
- The path to your **resampled images** is stored in `resampled_path`.
- The path to your **downloaded images** is stored in `dwl_path`.
- You have to loop through the spectral bands and find all the jp2 files corresponding to these spectral bands
</div>
%% Cell type:code id: tags:
``` python
list_im_to_clip =
for band in band_10m_list:
list_im_to_clip += glob.glob()
print(f'')
```
%% Cell type:markdown id: tags:
**Check if the ROI is located in one of the image to clip**
%% Cell type:code id: tags:
``` python
fig, ax = plt.subplots(1, 1, figsize=(10,10))
# Plot image
# First image of the list
im_file = list_im_to_clip[0]
# A cloudy image
#im_file = [s for s in list_im_to_clip if all(xs in s for xs in ['20200621','B04'])][0]
This function **clips a list of raster images** to the extent of a given region of interest (ROI).
#### **Arguments:**
1. **`list_im_to_clip`** *(list of str)* → A list of file paths to the images that need to be clipped.
2. **`clipped_path`** *(str)* → The directory where the clipped images will be saved.
3. **`roi_gdf`** *(GeoDataFrame)* → A GeoDataFrame containing the region of interest (ROI) geometry used for clipping.
#### **Process:**
- Iterates through each image file in `list_im_to_clip`.
- Generates the output filename by appending `_ROI.tif` to the original filename.
- Opens the raster file using `rasterio`.
- Clips the raster to the extent of the `roi_gdf` geometry using `rasterio.mask.mask()`.
- Updates the metadata to match the new clipped image dimensions and transformation.
- Writes the clipped image to a new **GeoTIFF (.tif)** file.
- Saves the clipped image to `clipped_path`.
</div>
%% Cell type:markdown id: tags:
<div class="alert alert-warning">
<h4 class="alert-heading"><strong>Third exercise of the session</strong></h4>
<hr>
### Exercise: Clip your images using the clip_imgs function
Your task is to use the `clip_imgs` function to clip all **10m resolution images** in `list_im_to_clip` to the extent of the provided **region of interest (ROI)**.
#### Steps:
1. Verify that all variables have already been defined above (your ROI GeoDataFrame, your list of images to clip, and the output path)
2. Run the functions with the correct arguments
</div>
%% Cell type:code id: tags:
``` python
from s2_func_prepro import clip_imgs
clip_imgs()
```
%% Cell type:markdown id: tags:
**Check if clipped image is located inside the ROI**
Atmospheric correction allows calculation of Bottom Of Atmosphere (BOA) reflectance from Top Of Atmosphere (TOA) reflectance images available in L1C products. For Sentinel-2 images, we will directly use the L2A data as available from the ground segment.
### 3.2 Cloud screening
Reliable identification of clouds and cloud shadows are necessary for any optical remote sensing image analysis, especially in operational and fully automatic setups. The cloud screening can be achieved using different algorithms (Sen2Cor, MAJA, Fmask). In this course we will work with Sen2Cor as the mask is already present in L2A products.
Scene Classification map (SCL) aims at providing a pixel classification map (cloud, cloud shadows, vegetation, soils/deserts, water, snow, etc.)
The SC algorithm enables:
- generation of a classification map which includes four different classes for clouds (including cirrus) and six different classifications for shadows, cloud shadows, vegetation, soils/deserts, water and snow
- provision of associated quality indicators corresponding to a map of cloud probability and a map of snow probability.
SCL class| Description
:---------:|:----------:
0| No data
1| Saturated or defective
2| Dark area pixels
3| Cloud shadows
4| Vegetation
5| Not vegetated
6| Water
7| Unclassified
8| Cloud medium probability
9| Cloud high probability
10| Thin cirrus
11| Snow
%% Cell type:markdown id: tags:
Get a list with all reflectance bands clipped on the ROI