Practical Course 22

Crop Stress Detection with Sentinel-2 Red Edge and DeepSeek

Learn to detect crop stress in North Morocco using Sentinel-2 red edge bands and the DeepSeek model for automated analysis, even with limited remote sensing experience.
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
NDRENormalized Difference Red EdgeAn index that uses red edge and near-infrared bands to assess plant health.
Red EdgeRed Edge BandsSpecific wavelengths sensitive to chlorophyll content in plants.
Sentinel-2Sentinel-2 MissionA European Earth observation mission providing high-resolution optical imagery.
GEEGoogle Earth EngineA cloud-based platform for geospatial data analysis.
Surface ReflectanceSurface ReflectanceThe proportion of light reflected from the Earth's surface after atmospheric correction.
Crop StressCrop StressEnvironmental factors negatively impacting plant health and productivity.
ROIRegion of InterestA specific geographic area selected for analysis.
Image CollectionImage CollectionA stack of images ordered by time in Google Earth Engine.
BandSpectral BandA specific range of wavelengths in the electromagnetic spectrum captured by a sensor.
ThresholdThresholdA value used to separate different classes or features in an image.
PixelPixelThe smallest unit of an image, representing a single value.
Cloud MaskingCloud MaskingThe process of removing cloud cover from satellite imagery.
NDVINormalized Difference Vegetation IndexA simple graphical indicator that assesses whether or not the target being observed contains live green vegetation.
DeepSeekDeepSeekA large language model used to interpret and analyze geospatial data.

Contents

  1. Introduction to Crop Stress and Remote Sensing
  2. Sentinel-2 and Red Edge Bands
  3. Google Earth Engine Setup
  4. Data Acquisition and Preprocessing
  5. NDRE Calculation
  6. Thresholding and Crop Stress Mapping
  7. DeepSeek Integration for Analysis
  8. Visualizing Results
  9. Accuracy Assessment
  10. Exporting Results
1
Introduction
10 min

Crop stress can significantly impact agricultural yields. Remote sensing, particularly using Sentinel-2 data, offers a powerful way to monitor crop health over large areas. This course will guide you through using Sentinel-2 red edge bands and Google Earth Engine to detect crop stress in North Morocco, enhanced by DeepSeek for automated analysis.

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 Crop Stress Detection with Sentinel-2 Red Edge 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 Course22_Crop Stress Detection with Sentinel-2 Red Edge 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 the provided Sentinel-2 NDRE image of the Rif Mountains and Middle Atlas regions of North Morocco for the date range 2023-06-01 to 2023-08-31, using the NDRE band. Identify areas of high and low crop stress. Provide a summary of the spatial distribution of crop stress, including the total area affected by low NDRE values (NDRE < 0.2). Suggest possible causes for the observed stress based on the geographical location and time of year. The image is created from the COPERNICUS/S2_SR dataset.
✨
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
Importing and Filtering Sentinel-2 Data
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.

Importing and Filtering Sentinel-2 Data
// Define the study area (North Morocco).
var roi = ee.Geometry.Polygon([[[-5.5, 32], [-3, 32], [-3, 35], [-5.5, 35]]]);

// Define the date range.
var startDate = '2023-06-01';
var endDate = '2023-08-31';

// Import Sentinel-2 SR data.
var s2 = ee.ImageCollection('COPERNICUS/S2_SR')
    .filterBounds(roi)
    .filterDate(startDate, endDate)
    .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20));

// Function to mask clouds using the QA60 band.
function maskS2clouds(image) {
  var qa = image.select('QA60');
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));
  return image.updateMask(mask).divide(10000); // Scale to 0-1
}
🔑
Beginner note: This code imports Sentinel-2 surface reflectance data, filters it by region, date, and cloud cover. It also defines a function to mask clouds using the QA60 band, which identifies cloudy pixels. The divide by 10000 scales the reflectance values to a 0-1 range.

5
Calculating NDRE and Mapping Crop Stress
10 min

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

Calculating NDRE and Mapping Crop Stress
// Apply cloud masking and calculate NDRE.
var s2_masked = s2.map(maskS2clouds);

var ndre = s2_masked.map(function(image) {
  return image.normalizedDifference(['B8A', 'B5']).rename('NDRE');
});

// Composite the NDRE images.
var ndre_composite = ndre.median();

// Define a threshold for crop stress (NDRE < 0.2).
var stress_threshold = 0.2;

// Create a binary mask for stressed areas.
var stressed_mask = ndre_composite.lt(stress_threshold);

// Visualize the results.
Map.centerObject(roi, 10);
Map.addLayer(ndre_composite, {min: 0, max: 0.7, palette: ['red', 'yellow', 'green']}, 'NDRE Composite');
Map.addLayer(stressed_mask.updateMask(stressed_mask), {palette: 'red'}, 'Stressed Areas');
🔑
Beginner note: This code calculates the Normalized Difference Red Edge (NDRE) using the B8A (NIR) and B5 (Red Edge) bands. It then creates a composite NDRE image and applies a threshold to identify areas of crop stress. Finally, it visualizes the NDRE composite and the stressed areas on the map.

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 stressed area mask to Google Drive.
Export.image.toDrive({
  image: stressed_mask,
  description: 'crop_stress_mask',
  folder: 'GEE_Exports',
  region: roi,
  scale: 10,
  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 Different Date Ranges

  1. Change the 'startDate' and 'endDate' variables to analyze crop stress in different seasons.
  2. Observe how the spatial distribution of stressed areas changes over time.

Adjusting the Stress Threshold

  1. Modify the 'stress_threshold' variable to identify different levels of crop stress.
  2. Analyze how the area of stressed regions changes with different threshold values.

Analyzing Specific Crops

  1. Create a more specific ROI focused on a particular agricultural area.
  2. Research the typical growing season and stress factors for the crops in that area.

Comparing with NDVI

  1. Calculate NDVI using the B8 and B4 bands.
  2. Compare the spatial patterns of NDRE and NDVI to understand their differences in detecting crop stress.

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 22 - Crop Stress Detection with Sentinel-2 Red Edge and DeepSeek | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026