Practical Course 17

Urban Green Space Analysis with NDVI and DeepSeek

Learn to analyze urban green spaces in North Morocco using NDVI from satellite imagery and AI-powered code generation.
North Morocco ~2 hours Master - Climate Change and GeoAI
Dataset: LANDSAT/LC08/C01/T1_SR Landsat 8 Surface Reflectance Tier 1

📖 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 measures the difference between near-infrared (which vegetation strongly reflects) and red light (which vegetation absorbs)
Landsat 8Landsat 8 SatelliteAn Earth observation satellite launched in 2013, providing moderate-resolution imagery of the Earth's surface.
Surface ReflectanceSurface ReflectanceThe fraction of incoming solar radiation that is reflected from the Earth's surface.
GEEGoogle Earth EngineA cloud-based platform for planetary-scale geospatial analysis.
Image CollectionImage CollectionA stack or time series of images in Google Earth Engine.
BandSpectral BandA specific range of wavelengths in the electromagnetic spectrum that a sensor is sensitive to.
PixelPicture ElementThe smallest addressable element in an image.
Cloud MaskingCloud MaskingThe process of identifying and removing clouds from satellite imagery.
Urban Green SpaceUrban Green SpaceAreas covered with vegetation in urban environments, such as parks, gardens, and street trees.
Rif MountainsRif MountainsA mountain range in northern Morocco.
Middle AtlasMiddle AtlasA mountain range in Morocco, part of the Atlas Mountains system.
DeepSeekDeepSeek CoderAn AI model specialized in code generation and completion, useful for scripting in GEE.
CompositeImage CompositeA single image created by combining multiple images, often used to reduce cloud cover.
ReducerReducerA function in GEE that aggregates data, such as calculating the mean value over a region.

Contents

  1. Introduction to Urban Green Space Analysis
  2. Understanding NDVI and Landsat 8
  3. Setting up Google Earth Engine
  4. Filtering and Cloud Masking Landsat Imagery
  5. Calculating NDVI
  6. Visualizing NDVI
  7. Analyzing NDVI in Urban Areas of North Morocco
  8. Using DeepSeek for Code Generation
  9. Exporting Results
  10. Conclusion and Further Exploration
1
Introduction
10 min

This course introduces the fundamentals of analyzing urban green space using remote sensing data and Google Earth Engine (GEE). We'll focus on calculating the Normalized Difference Vegetation Index (NDVI) from Landsat 8 imagery to assess vegetation health in urban areas of North Morocco. Additionally, we'll explore how to leverage AI tools like DeepSeek to assist in code generation for GEE.

GEE Asset ID
LANDSAT/LC08/C01/T1_SR
Dataset Name
Landsat 8 Surface Reflectance Tier 1
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 Urban Green Space Analysis with NDVI 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 Course17_Urban Green Space Analysis with NDVI 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
Write a Google Earth Engine script to calculate NDVI from Landsat 8 surface reflectance imagery for the Rif Mountains and Middle Atlas region of North Morocco between 2022-01-01 and 2022-12-31. Include cloud masking using the pixel_qa band. Calculate the mean NDVI for urban areas. Output a map showing NDVI values.
✨
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
Setting up the Environment and Filtering 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.

Setting up the Environment and Filtering Data
// Define the region of interest (Rif Mountains and Middle Atlas)
var roi = ee.Geometry.Polygon([
    [-5.5, 35.0], [-3.5, 35.0], [-3.5, 33.0], [-5.5, 33.0]
]);

// Define the date range
var startDate = '2022-01-01';
var endDate = '2022-12-31';

// Load Landsat 8 surface reflectance data
var landsat8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
    .filterDate(startDate, endDate)
    .filterBounds(roi);
🔑
Beginner note: This code block initializes the analysis by defining the region of interest (ROI) as a polygon covering the Rif Mountains and Middle Atlas. It then sets the start and end dates for the analysis period. Finally, it loads the Landsat 8 surface reflectance image collection from Google Earth Engine and filters it by date and region.

5
Cloud Masking and NDVI Calculation
10 min

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

Cloud Masking and NDVI Calculation
// Function to mask clouds using the pixel_qa band
var maskClouds = function(image) {
  var qa = image.select('pixel_qa');
  var cloudBitMask = 1 << 5;
  var cloudShadowBitMask = 1 << 3;
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cloudShadowBitMask).eq(0));
  return image.updateMask(mask);
};

// Apply cloud masking
var landsat8_masked = landsat8.map(maskClouds);

// Function to calculate NDVI
var calculateNDVI = function(image) {
  return image.normalizedDifference(['B5', 'B4']).rename('NDVI');
};

// Calculate NDVI for each image
var ndviCollection = landsat8_masked.map(calculateNDVI);
🔑
Beginner note: This code block defines a function to mask clouds in the Landsat 8 imagery using the pixel_qa band. It then applies this cloud masking function to the entire image collection. After cloud masking, it defines another function to calculate NDVI using the near-infrared (B5) and red (B4) bands. Finally, it applies the NDVI calculation function to the cloud-masked image collection.

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
// Composite the NDVI collection and export the mean NDVI image.
var ndvi_composite = ndviCollection.median();

Export.image.toDrive({
  image: ndvi_composite,
  description: 'NDVI_North_Morocco_2022',
  folder: 'GEE_Exports',
  region: roi,
  scale: 30,
  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 Regions

  1. Change the ROI to focus on a specific city within North Morocco (e.g., Tangier, Fez).
  2. Re-run the analysis and observe how the NDVI values differ from the original region.

Analyzing Different Time Periods

  1. Modify the start and end dates to analyze NDVI during a different season or year.
  2. Compare the NDVI values between different time periods to observe seasonal changes in vegetation.

Improving Cloud Masking

  1. Research alternative cloud masking techniques in Google Earth Engine.
  2. Implement a different cloud masking algorithm and compare the results with the original method.

Integrating Land Use Data

  1. Find a land use dataset for North Morocco in GEE.
  2. Overlay the land use data with the NDVI results to analyze the relationship between land use and vegetation health.

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 IDLANDSAT/LC08/C01/T1_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 17 - Urban Green Space Analysis with NDVI and DeepSeek | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026