Practical Course 7

Coastal Erosion Detection with Sentinel-2 and DeepSeek

Learn to monitor coastal changes using satellite imagery and AI to understand the impact of erosion in North Morocco.
North Morocco ~2 hours Master - Climate Change and GeoAI
Dataset: COPERNICUS/S2_SR Sentinel-2 Surface Reflectance

📖 Key Terms for Beginners

Before starting, make sure you understand these terms. They appear throughout all code blocks in this course.

TermFull NameWhat it means in simple words
NDWINormalized Difference Water IndexA remote sensing index used to detect and monitor changes in water content.
Sentinel-2Sentinel-2 MissionAn Earth observation mission from the Copernicus Programme that systematically acquires optical imagery at high spatial resolution.
Surface ReflectanceSurface ReflectanceThe fraction of incoming solar radiation reflected from the Earth's surface.
Coastal ErosionCoastal ErosionThe wearing away and loss of land along the coastline due to natural forces.
GEEGoogle Earth EngineA cloud-based platform for planetary-scale geospatial analysis.
DeepSeekDeepSeek LLMA large language model used for various tasks, including image analysis and interpretation.
BandSpectral BandA specific range of wavelengths in the electromagnetic spectrum that a sensor is designed to detect.
Cloud MaskingCloud MaskingThe process of identifying and removing clouds from satellite imagery.
Image CollectionImage CollectionA collection of images organized in Google Earth Engine.
Median CompositeMedian CompositeA method of combining multiple images to reduce noise and cloud cover by selecting the median pixel value for each location.
ClassificationImage ClassificationThe process of assigning pixels in an image to different categories or classes.
Feature ExtractionFeature ExtractionThe process of identifying and measuring relevant characteristics from an image.
GISGeographic Information SystemA system designed to capture, store, manipulate, analyze, manage, and present spatial or geographic data.

Contents

  1. Introduction to Coastal Erosion
  2. Sentinel-2 Data Acquisition
  3. Cloud Masking and Preprocessing
  4. NDWI Calculation
  5. Time Series Analysis
  6. DeepSeek Integration
  7. Erosion Detection Workflow
  8. Accuracy Assessment
  9. Visualization and Mapping
  10. Conclusion
1
Introduction
10 min

Coastal erosion is a significant environmental challenge, especially in regions like North Morocco. This course will guide you through using Sentinel-2 satellite imagery and the power of DeepSeek to detect and monitor coastal changes. You'll learn to analyze time series data and develop a workflow for identifying areas at risk of erosion.

GEE Asset ID
COPERNICUS/S2_SR
Dataset Name
Sentinel-2 Surface Reflectance
Study Area
North Morocco
AI Tool
DeepSeek (free, no API key needed)
🌍
What you will build: By the end of this course you will have a working GEE script that analyzes Coastal Erosion Detection with Sentinel-2 and DeepSeek, computes statistics, visualizes results on an interactive map, and exports data to Google Drive.

2
Setup: GEE + DeepSeek
5 min

You need two browser tabs open side by side throughout this course.

1
Open chat.deepseek.com -- free account, no API key needed
2
Open code.earthengine.google.com in a second tab
3
Create a new GEE script named Course7_Coastal Erosion Detection with Sentinel-2 and DeepSeek
💡
Workflow: Write a prompt in DeepSeek describing your task with exact dataset IDs and requirements. Copy the generated GEE JavaScript. Paste into GEE code editor. Click Run. Inspect results. Iterate.

3
Crafting the DeepSeek Prompt
15 min

The prompt is the core skill of this course. A good prompt includes the exact dataset ID, band names, study area coordinates, dates, preprocessing steps, and desired outputs.

📋 Main Prompt -- copy and paste this into DeepSeek
Analyze Sentinel-2 satellite imagery from the North Morocco coast near Al Hoceima between 2020 and 2024 (COPERNICUS/S2_SR). Identify areas of coastal erosion. Use NDWI to detect water boundaries. Provide a report summarizing the areas with the most significant erosion, including their geographic coordinates and the estimated amount of land lost per year. Highlight potential causes of the erosion based on the satellite imagery (e.g., construction, natural processes). Include specific band information (B2, B3, B4, B8, B11).
✨
After pasting the prompt: Wait 20-30 seconds for DeepSeek to generate the full GEE script. Copy the entire code block it produces. If the output is cut short, type "Continue the code" to get the rest.

4
Data Acquisition and Cloud Masking
10 min

Paste the following code into your GEE code editor and click Run. Read the beginner notes below to understand what each line does.

Data Acquisition and Cloud Masking
// Define the region of interest (North Morocco).
var roi = ee.Geometry.Rectangle([-4.0, 35.0, -3.5, 35.5]);

// Define the date range.
var startDate = '2020-01-01';
var endDate = '2024-01-01';

// Function to mask clouds using the QA60 band.
var maskS2clouds = function(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 mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(
             qa.bitwiseAnd(cirrusBitMask).eq(0));
  return image.updateMask(mask).clip(roi);
};

// Load Sentinel-2 SR data, filter by region and date, and apply cloud masking.
var collection = ee.ImageCollection('COPERNICUS/S2_SR')
    .filterDate(startDate, endDate)
    .filterBounds(roi)
    .map(maskS2clouds);
🔑
Beginner note: This code block first defines the region of interest (ROI) and the date range for analysis. Then, it defines a function `maskS2clouds` to mask clouds using the QA60 band of Sentinel-2, which contains cloud and cirrus information. The `bitwiseAnd` function checks if the cloud and cirrus bits are set to zero, indicating clear conditions. Finally, it loads the Sentinel-2 Surface Reflectance data, filters it by date and region, and applies the cloud masking function.

5
NDWI Calculation and Visualization
10 min

Add this block after the previous code. It continues the analysis with additional processing and visualization.

NDWI Calculation and Visualization
// Function to calculate NDWI.
var calculateNDWI = function(image) {
  return image.normalizedDifference(['B3', 'B8']).rename('NDWI');
};

// Calculate NDWI for each image in the collection.
var ndwiCollection = collection.map(calculateNDWI);

// Create a median composite of NDWI.
var ndwiMedian = ndwiCollection.median().clip(roi);

// Define visualization parameters.
var ndwiVisParams = {
  min: -1,  
  max: 1,  
  palette: ['blue', 'white', 'green']
};

// Add the NDWI layer to the map.
Map.addLayer(ndwiMedian, ndwiVisParams, 'NDWI Median');
Map.centerObject(roi, 12);
🔑
Beginner note: This code block defines a function `calculateNDWI` to compute the Normalized Difference Water Index (NDWI) using the green (B3) and NIR (B8) bands. It then applies this function to each image in the collection. A median composite of NDWI is created to reduce noise. Finally, visualization parameters are defined, and the NDWI layer is added to the map, centered on the region of interest.

6
Export Results to Google Drive
5 min

Add this block at the end of your script to export the final map as a GeoTIFF to your Google Drive. After clicking Run, go to the Tasks tab in GEE and click Run next to each export task.

Export to Google Drive
// Export the NDWI median composite to Google Drive.
Export.image.toDrive({
  image: ndwiMedian,
  description: 'NDWI_Median_NorthMorocco',
  folder: 'GEE_Exports',
  scale: 10, // Sentinel-2 resolution
  region: roi,
  maxPixels: 1e13
});
🔑
Beginner note -- Export.image.toDrive(): This function does not export immediately. It creates a task in the GEE Tasks tab that you must manually start by clicking Run. The file will appear in your Google Drive folder (GEE_Courses) as a GeoTIFF that you can open in QGIS or ArcGIS.

7
Exercises Using DeepSeek Prompts
Homework

Use DeepSeek to extend the script for each exercise below. Write a follow-up prompt describing what you want to add, then copy the generated code and paste it into your GEE script.

Modify the Date Range

  1. Change the `startDate` and `endDate` variables to analyze a different time period.
  2. Observe how the NDWI changes over the new time period.

Explore Different Regions

  1. Change the `roi` variable to analyze a different coastal area in North Morocco.
  2. Adjust the map center and zoom level to the new region.

Calculate MNDWI

  1. Implement the Modified Normalized Difference Water Index (MNDWI) using the SWIR band (B11) instead of the NIR band.
  2. Compare the results with the standard NDWI.

Visualize with Different Palettes

  1. Experiment with different color palettes for visualizing the NDWI.
  2. Use the `palette` parameter in the `ndwiVisParams` to try different color combinations.

8
Prompt Engineering Tips
Reference

To get the best results from DeepSeek for GEE tasks, always include these elements in your prompts:

ElementExample
Exact dataset IDCOPERNICUS/S2_SR
Band names"select band 'B4' for red, 'B8' for NIR"
Study area"rectangle [-6.5, 33.0, -1.5, 36.0] North Morocco"
Date range"filter from 2020-01-01 to 2023-12-31"
Output format"print area in hectares, add a legend, export to Drive"
Error fixing"The code gives error X. Please fix it."
Iteration"Add a time series chart for each year 2018-2023"
🧠
Best practice: Start with the main prompt, run the code, then send follow-up prompts to add features one at a time. This gives you cleaner, more reliable code than asking for everything at once.
Course 7 - Coastal Erosion Detection with Sentinel-2 and DeepSeek | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026