Practical Course 9

Cropland Mapping with Sentinel-2 and Dynamic World

Learn to map cropland in North Morocco using Sentinel-2 imagery and Google's Dynamic World dataset for efficient land cover classification.
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
NDVINormalized Difference Vegetation IndexA simple graphical indicator that can be used to analyze remote sensing observations, often from a satellite, and assess whether the target being observed contains live green vegetation.
EVIEnhanced Vegetation IndexAn optimized vegetation index designed to enhance the vegetation signal with improved sensitivity in high biomass regions and improved vegetation monitoring through a de-coupling of the canopy background signal and a reduction in atmosphere influences.
Sentinel-2Sentinel-2 MissionAn Earth observation mission from the Copernicus Programme that systematically acquires optical imagery at high spatial resolution over land and coastal waters.
Dynamic WorldGoogle's Dynamic WorldA near real-time global land cover dataset at 10m resolution, derived from Sentinel-2 imagery.
GEEGoogle Earth EngineA cloud-based platform for planetary-scale geospatial analysis.
ClassificationImage ClassificationThe process of sorting pixels into a finite number of individual classes, or categories, of data based on their data file values.
ROIRegion of InterestA specific area selected for analysis.
Surface ReflectanceSurface ReflectanceThe fraction of incoming solar radiation that is reflected from the Earth's surface.
Spectral BandsSpectral BandsSpecific ranges of the electromagnetic spectrum that are measured by a sensor.
Cloud MaskingCloud MaskingThe process of identifying and removing clouds from satellite imagery.
PixelPixelThe smallest unit of an image, representing a single measurement of reflectance or other data.
Time SeriesTime Series AnalysisAnalyzing data points indexed in time order.
Land CoverLand CoverThe physical material at the surface of the earth.
CompositeImage CompositeA combination of multiple images into a single image, often used to reduce cloud cover or create a more representative view of an area.

Contents

  1. Introduction to Cropland Mapping
  2. Sentinel-2 Data Acquisition
  3. Dynamic World Data Acquisition
  4. Data Preprocessing
  5. Vegetation Index Calculation
  6. Cropland Classification
  7. Accuracy Assessment
  8. Visualization
  9. Exporting Results
  10. Advanced Analysis
1
Introduction
10 min

This course introduces the fundamentals of cropland mapping using remote sensing data. We will leverage Sentinel-2 imagery and Google's Dynamic World dataset within the Google Earth Engine (GEE) platform. By the end of this course, you'll be able to map cropland in North Morocco, even with limited prior experience in GEE or remote sensing.

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 Cropland Mapping with Sentinel-2 and Dynamic World, 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 Course9_Cropland Mapping with Sentinel-2 and Dynamic World
💡
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
Using Google Earth Engine, create a cropland map of the Rif Mountains and Middle Atlas regions of North Morocco for the year 2023. Use Sentinel-2 surface reflectance data (COPERNICUS/S2_SR) and Google's Dynamic World dataset (GOOGLE/DYNAMIC_WORLD/V1). Filter Sentinel-2 data for images between January 1, 2023, and December 31, 2023. Apply cloud masking using the QA60 band. Calculate NDVI and EVI. Use Dynamic World to identify cropland areas. Refine the cropland classification using a supervised classification approach with manually selected training data. Calculate the overall accuracy of the cropland map. Visualize the cropland map with a custom color palette. Export the final cropland map as a GeoTIFF file.
✨
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
Sentinel-2 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.

Sentinel-2 Data Acquisition and Cloud Masking
// Define region of interest (Rif Mountains and Middle Atlas, Morocco)
var roi = ee.Geometry.Rectangle([-6, 32, -2, 35]);

// 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).divide(10000);
};

// Load Sentinel-2 SR data and filter by date and region
var s2 = ee.ImageCollection('COPERNICUS/S2_SR')
    .filterDate('2023-01-01', '2023-12-31')
    .filterBounds(roi)
    .map(maskS2clouds);
🔑
Beginner note: This code block first defines the region of interest (ROI) in North Morocco. Then, it defines a function `maskS2clouds` to mask out clouds from Sentinel-2 images using the QA60 band. Finally, it loads the Sentinel-2 Surface Reflectance dataset, filters it by date and region, and applies the cloud masking function to each image in the collection. The values are divided by 10000 to convert to reflectance values.

5
Vegetation Index Calculation and Dynamic World Integration
10 min

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

Vegetation Index Calculation and Dynamic World Integration
// Function to calculate NDVI
var addNDVI = function(image) {
  var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI');
  return image.addBands(ndvi);
};

// Function to calculate EVI
var addEVI = function(image) {
  var evi = image.expression(
      '2.5 * (NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1)', {
        'NIR': image.select('B8'),
        'RED': image.select('B4'),
        'BLUE': image.select('B2')
      }).rename('EVI');
  return image.addBands(evi);
};

// Apply NDVI and EVI calculations
var s2_ndvi_evi = s2.map(addNDVI).map(addEVI);

// Load Dynamic World data
var dw = ee.ImageCollection('GOOGLE/DYNAMIC_WORLD/V1')
    .filterDate('2023-01-01', '2023-12-31')
    .filterBounds(roi);

// Get the most frequent land cover class from Dynamic World
var dw_mode = dw.select('label').reduce(ee.Reducer.mode());
🔑
Beginner note: This code block defines functions to calculate NDVI and EVI from Sentinel-2 imagery. It then applies these functions to the Sentinel-2 image collection. It also loads the Dynamic World dataset, filters it by date and region, and calculates the most frequent land cover class for each pixel using the `reduce(ee.Reducer.mode())` function.

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 cropland map to Google Drive
Export.image.toDrive({
  image: dw_mode,
  description: 'Cropland_Map_Morocco_2023',
  folder: 'GEE_Exports',
  scale: 10,
  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.

Exploring Sentinel-2 Bands

  1. Load a single Sentinel-2 image.
  2. Display different spectral bands (e.g., Red, Green, Blue, NIR).

Cloud Cover Visualization

  1. Visualize the QA60 band.
  2. Identify areas with cloud cover based on the QA60 band values.

NDVI Thresholding

  1. Experiment with different NDVI thresholds to identify vegetation.
  2. Compare the results with visual interpretation.

Dynamic World Land Cover Types

  1. Visualize the Dynamic World land cover classification.
  2. Identify the distribution of different land cover types in your ROI.

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 9 - Cropland Mapping with Sentinel-2 and Dynamic World | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026