import os, sys, subprocessIN_COLAB = "google.colab" in sys.modulestry: import eeexcept ImportError: # local Jupyter without the package subprocess.run([sys.executable, "-m", "pip", "install", "-q", "earthengine-api"], check=True) import eefrom IPython.display import Image, display # to show Earth Engine thumbnailsPROJECT_ID = "your-cloud-project" # <-- replace with your Earth Engine Cloud project IDPROJECT_ID = os.environ.get("EE_PROJECT", PROJECT_ID) # optional: set EE_PROJECT when running locallyif PROJECT_ID == "your-cloud-project": raise ValueError("Set PROJECT_ID to your own Earth Engine Cloud project ID (see the instructions above).")ee.Authenticate() # no-op if valid credentials already existee.Initialize(project=PROJECT_ID)print(f"✓ Earth Engine initialised (project: {PROJECT_ID}, earthengine-api {ee.__version__})")Day 1, Session 4: Google Earth Engine Python API
EO AI/ML Training · Hands-on notebook
Learning objectives
By the end of this notebook you will be able to:
- Authenticate and initialise Google Earth Engine (GEE) in Python with a Cloud project
- Use the core GEE objects: Geometry, Image, ImageCollection, Feature, FeatureCollection
- Filter Sentinel-2 and Sentinel-1 collections by place, time and metadata
- Mask clouds with Cloud Score+ and build median composites
- Calculate NDVI and summarise it over an area (reducers)
- Export images and training samples for AI/ML workflows
- Know when to use GEE and when to move to local / Colab processing
What you’ll need
| Runtime | Google Colab (recommended; earthengine-api and geemap are pre-installed) or local Jupyter |
| Account | A Google account and a Google Cloud project registered for Earth Engine (free for non-commercial use) — see Section 1 |
| Data | None to download: everything runs on Earth Engine servers |
| Time | ~2 hours including three exercises |
Prerequisites: Session 3 (Python geospatial basics); Session 1 (Sentinel-1/2).
—## 1. Setup and AuthenticationEarth Engine requires every request to be attached to a Google Cloud project that is registered for Earth Engine.One-time setup (5 minutes):1. Go to https://code.earthengine.google.com/register and sign in with your Google account2. Choose non-commercial use (education, research, government, non-profit) and create a new Cloud project (or select an existing one)3. Copy the Project ID (looks like my-ee-project-123456) and paste it belowEvery session: run ee.Authenticate() (opens a Google sign-in; on Colab it reuses your notebook login) and ee.Initialize(project=PROJECT_ID).
Troubleshooting| Message | Fix ||—|—|| ValueError: Set PROJECT_ID… | Replace your-cloud-project with your project ID (or set the EE_PROJECT environment variable) || ee.Initialize: no project found / Project … is not registered | Register the project for Earth Engine at https://code.earthengine.google.com/register || Earth Engine API has not been used in project … | Enable the API: https://console.cloud.google.com/apis/library/earthengine.googleapis.com || PERMISSION_DENIED | Authenticate with the same Google account that owns (or has access to) the project |
—## 2. Core Earth Engine ConceptsEarth Engine code builds a recipe on your computer; nothing is computed until you ask for a result (.getInfo(), a thumbnail, an export). Keep .getInfo() for small results only.### 2.1 Geometry
manila_point = ee.Geometry.Point([121.0, 14.6]) # [lon, lat]palawan_bbox = ee.Geometry.Rectangle([117.5, 8.5, 119.5, 11.5]) # [xmin, ymin, xmax, ymax]custom_polygon = ee.Geometry.Polygon([[[120.8, 14.4], [121.2, 14.4], [121.2, 14.8], [120.8, 14.8]]])print("Point:", manila_point.getInfo())print("Rectangle area (km²):", round(palawan_bbox.area(maxError=100).divide(1e6).getInfo()))print("10 km buffer area (km²):", round(manila_point.buffer(10_000).area(maxError=1).divide(1e6).getInfo(), 1))# Expected: ≈ 314 km² (π × 10²)2.2 Image and ImageCollection
# A single image: SRTM 30 m elevationdem = ee.Image("USGS/SRTMGL1_003")print("DEM bands:", dem.bandNames().getInfo())print("Elevation at Mt Apo summit area (m):", dem.sample(ee.Geometry.Point([125.27, 6.99]), scale=30).first().get("elevation").getInfo())# A collection: all Sentinel-2 L2A images (harmonised to remove the 2022 offset change)s2_all = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")first = s2_all.filterBounds(manila_point).filterDate("2024-01-01", "2024-01-31").first()print("\nFirst Jan-2024 S2 image over Manila:", first.get("system:index").getInfo())print("Band names:", first.bandNames().getInfo())2.3 Feature and FeatureCollectionFeatures are vector data: a geometry plus properties.
cities = ee.FeatureCollection([ ee.Feature(ee.Geometry.Point([121.00, 14.60]), {"name": "Manila"}), ee.Feature(ee.Geometry.Point([125.61, 7.07]), {"name": "Davao"}), ee.Feature(ee.Geometry.Point([123.89, 10.32]), {"name": "Cebu"}),])print("Number of cities:", cities.size().getInfo())print("Names:", cities.aggregate_array("name").getInfo())2.4 Filters and reducers- Filters select images or features: .filterBounds(geom), .filterDate(start, end), .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 30))- Reducers summarise: over time (collection.median()), over space (image.reduceRegion(...)), over features (aggregate_*)(filterMetadata is deprecated — use .filter(ee.Filter.lt(...)).)
—## 3. Working with Sentinel-2### 3.1 Area of interest and collectionWe work over central Palawan (Puerto Princesa and surroundings) in the 2024 dry season (January–April), when cloud cover is lowest.
aoi = ee.Geometry.Rectangle([118.4, 9.5, 119.0, 10.1]) # ~65 x 65 km around Puerto Princesastart_date, end_date = "2024-01-01", "2024-04-30"s2 = (ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED") .filterBounds(aoi) .filterDate(start_date, end_date) .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 60)))print(f"AOI area: {aoi.area(maxError=100).divide(1e6).getInfo():,.0f} km²")print(f"Sentinel-2 images found: {s2.size().getInfo()}")info = s2.aggregate_array("system:index").getInfo()[:10]clouds = s2.aggregate_array("CLOUDY_PIXEL_PERCENTAGE").getInfo()[:10]for idx, cc in zip(info, clouds): print(f" {idx[:8]} cloud {cc:5.1f}% tile {idx.split('_')[-1]}")3.2 Cloud masking with Cloud Score+Beware of the classic QA60 bitmask: in Earth Engine it is masked out (empty) from 25 January 2022 to 28 February 2024, so a QA60-based mask removes every pixel in that period (since March 2024 it is rebuilt from the MSK_CLASSI bands). Google’s Cloud Score+ (GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED) gives every pixel a clear-sky score from 0 (cloud/shadow) to 1 (clear); we keep pixels with cs_cdf ≥ 0.6. An alternative is the Sentinel-2 Scene Classification Layer (SCL band), see Session 1.
cs_plus = ee.ImageCollection("GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED")CLEAR_THRESHOLD = 0.60def mask_clouds(image): """Keep pixels whose Cloud Score+ cs_cdf is above the threshold.""" return image.updateMask(image.select("cs_cdf").gte(CLEAR_THRESHOLD))s2_masked = s2.linkCollection(cs_plus, ["cs_cdf"]).map(mask_clouds)composite = s2_masked.median().clip(aoi)print("✓ Cloud-masked median composite created")print("Bands:", composite.bandNames().getInfo()[:13])Why the median? For each pixel it takes the middle value over time, which ignores the remaining bright clouds and dark shadows better than the mean.
3.3 Visualise with thumbnails
vis_rgb = {"bands": ["B4", "B3", "B2"], "min": 0, "max": 2500, "gamma": 1.2}vis_false = {"bands": ["B8", "B4", "B3"], "min": 0, "max": 4000, "gamma": 1.2}print("True colour (B4-B3-B2):")display(Image(url=composite.getThumbURL({"region": aoi, "dimensions": 512, **vis_rgb})))print("False colour (B8-B4-B3): vegetation appears red")display(Image(url=composite.getThumbURL({"region": aoi, "dimensions": 512, **vis_false})))Optional: an interactive map with geemap (pre-installed on Colab; locally pip install geemap).
try: import geemap m = geemap.Map(center=[9.8, 118.7], zoom=10) m.addLayer(composite, vis_rgb, "S2 true colour 2024 dry season") m.addLayer(aoi, {"color": "yellow"}, "AOI", False) display(m)except ImportError: print("geemap not installed - thumbnails above are enough for this notebook")3.4 NDVI and regional statisticsnormalizedDifference(["B8", "B4"]) computes (B8 − B4) / (B8 + B4). reduceRegion summarises it over the AOI; we use scale=100 for a quick answer (10 m would process 100× more pixels for almost the same mean).
ndvi = composite.normalizedDifference(["B8", "B4"]).rename("NDVI")stats = ndvi.reduceRegion( reducer=ee.Reducer.mean().combine(ee.Reducer.percentile([5, 50, 95]), sharedInputs=True), geometry=aoi, scale=100, maxPixels=1e9,).getInfo()for k, v in stats.items(): print(f" {k:<10} {v:.3f}")vis_ndvi = {"min": -0.2, "max": 0.9, "palette": ["blue", "white", "yellow", "green", "darkgreen"]}display(Image(url=ndvi.getThumbURL({"region": aoi, "dimensions": 512, **vis_ndvi})))Reading the map: blue = water (Sulu Sea, Puerto Princesa Bay), white/yellow = urban, bare or sparse cover, green = vegetation, dark green = dense forest.
📝 Exercise 1: Another place, another seasonRepeat 3.1–3.4 for a different Philippine location and the wet season (June–October 2024). Compare the number of images found and how clean the composite is.Suggested AOIs: Metro Manila [120.9, 14.4, 121.1, 14.7] · Davao [125.3, 6.9, 125.7, 7.3] · Cebu [123.7, 10.2, 124.0, 10.5]Expected output: an image count and a true-colour thumbnail. Wet-season composites usually have more gaps/haze.
# TODO: Exercise 1my_aoi = ee.Geometry.Rectangle([120.9, 14.4, 121.1, 14.7])my_start, my_end = "2024-06-01", "2024-10-31"# my_s2 = ...# my_composite = ...# display(Image(url=my_composite.getThumbURL(...)))Show solution
pythonmy_s2 = (ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED") .filterBounds(my_aoi).filterDate(my_start, my_end) .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 60)) .linkCollection(cs_plus, ["cs_cdf"]).map(mask_clouds))print("Images found:", my_s2.size().getInfo())my_composite = my_s2.median().clip(my_aoi)display(Image(url=my_composite.getThumbURL({"region": my_aoi, "dimensions": 512, **vis_rgb})))
—## 4. Working with Sentinel-1 SARSentinel-1 C-band radar sees through clouds, day and night — essential in the Philippine rainy season. The GEE collection COPERNICUS/S1_GRD is already calibrated, terrain-corrected and in decibels (dB).### 4.1 Filter the collection
s1 = (ee.ImageCollection("COPERNICUS/S1_GRD") .filterBounds(aoi) .filterDate(start_date, end_date) .filter(ee.Filter.eq("instrumentMode", "IW")) .filter(ee.Filter.listContains("transmitterReceiverPolarisation", "VV")) .filter(ee.Filter.listContains("transmitterReceiverPolarisation", "VH")) .filter(ee.Filter.eq("orbitProperties_pass", "DESCENDING")))print(f"Sentinel-1 images found: {s1.size().getInfo()}")print("Platforms:", sorted(set(s1.aggregate_array("platform_number").getInfo())))- IW (Interferometric Wide swath, 250 km): the standard land mode- VV + VH: VV responds to surface roughness (water, built-up), VH to volume scattering (vegetation)- One orbit direction: descending passes are around 6 am local time, ascending around 6 pm; mixing them mixes viewing geometries
4.2 Composite and polarisation ratio
s1_composite = s1.select(["VV", "VH"]).mean().clip(aoi) # temporal mean reduces speckle# In dB a ratio is a DIFFERENCE: VV/VH (linear) = VV_dB - VH_dBvv_minus_vh = s1_composite.select("VV").subtract(s1_composite.select("VH")).rename("VV_minus_VH")vis_vv = {"bands": ["VV"], "min": -25, "max": 0}print("VV backscatter (dB): dark = water / smooth surfaces, bright = built-up / rough terrain")display(Image(url=s1_composite.getThumbURL({"region": aoi, "dimensions": 512, **vis_vv})))sar_rgb = ee.Image.cat([s1_composite.select("VV"), s1_composite.select("VH"), vv_minus_vh])print("SAR colour composite (R = VV, G = VH, B = VV−VH)")display(Image(url=sar_rgb.getThumbURL({"region": aoi, "dimensions": 512, "min": [-25, -30, 0], "max": [0, -5, 15]})))📝 Exercise 2: VV vs VHDisplay VV and VH thumbnails side by side (use "min": -30, "max": -5 for VH). Where do they differ most?Expected output: two thumbnails; forests are relatively brighter in VH than in VV, water is dark in both.
# TODO: Exercise 2# vis_vh = ...# display(...)Show solution
pythonvis_vh = {"bands": ["VH"], "min": -30, "max": -5}print("VV"); display(Image(url=s1_composite.getThumbURL({"region": aoi, "dimensions": 400, **vis_vv})))print("VH"); display(Image(url=s1_composite.getThumbURL({"region": aoi, "dimensions": 400, **vis_vh})))VV is best for water and built-up areas; VH for vegetation structure. Using both improves classification (Day 2) and flood mapping (Day 3).
—## 5. Exporting Data for AI/MLLarge results are exported as background tasks (to Google Drive, Cloud Storage or an Earth Engine asset) instead of downloaded with .getInfo(). We export a small 20 × 20 km subset in UTM zone 50N (EPSG:32650), the native projection of Sentinel-2 tiles over Palawan.### 5.1 Export an image to Google Drive
export_aoi = ee.Geometry.Rectangle([118.65, 9.70, 118.85, 9.90]) # ~20 x 20 km, Puerto Princesatask_s2 = ee.batch.Export.image.toDrive( image=composite.select(["B2", "B3", "B4", "B8", "B11", "B12"]).toUint16(), description="Palawan_S2_composite_2024dry", folder="EarthEngine_Exports", fileNamePrefix="palawan_s2_composite_2024dry", region=export_aoi, scale=10, crs="EPSG:32650", maxPixels=1e9,)task_s2.start()print(f"Export started, task id {task_s2.id}. Monitor it in the Code Editor 'Tasks' tab or below.")5.2 Check task status
import timefor _ in range(6): state = task_s2.status()["state"] print(state) if state in ("COMPLETED", "FAILED", "CANCELLED"): break time.sleep(10)if state == "FAILED": print(task_s2.status().get("error_message"))Exports usually take a few minutes; you can continue with the notebook while they run. The file appears in My Drive/EarthEngine_Exports/.
5.3 Export sample points as a table
samples = composite.select(["B2", "B3", "B4", "B8", "B11", "B12"]).addBands(ndvi).sample( region=export_aoi, scale=10, numPixels=1000, seed=42, geometries=True)print("Samples:", samples.size().getInfo())task_samples = ee.batch.Export.table.toDrive( collection=samples, description="Palawan_samples_2024dry", folder="EarthEngine_Exports", fileNamePrefix="palawan_samples_2024dry", fileFormat="CSV")task_samples.start()print(f"Table export started, task id {task_samples.id}")📝 Exercise 3: Export your own compositeExport the RGB bands (B2, B3, B4) of your Exercise 1 composite for a small (≤ 20 × 20 km) part of your AOI, at 10 m, with a meaningful file name. Pick the UTM zone of your area: EPSG:32651 for Luzon/Visayas, EPSG:32650 for Palawan, EPSG:32651/32652 for Mindanao (west/east of 126°E).Expected output: a task id and, a few minutes later, a GeoTIFF in your Drive.
# TODO: Exercise 3# my_task = ee.batch.Export.image.toDrive(...)# my_task.start()Show solution
pythonsmall = ee.Geometry.Rectangle([120.95, 14.50, 121.10, 14.65])my_task = ee.batch.Export.image.toDrive( image=my_composite.select(["B2", "B3", "B4"]).toUint16(), description="Manila_S2_wet2024", folder="EarthEngine_Exports", fileNamePrefix="manila_s2_wet2024", region=small, scale=10, crs="EPSG:32651", maxPixels=1e9)my_task.start()print(my_task.id)
—## 6. From Earth Engine to Machine Learning### 6.1 A multi-sensor feature stackMachine-learning classifiers work on a stack of features per pixel. Here: six optical bands, NDVI and two SAR bands.
ml_stack = (composite.select(["B2", "B3", "B4", "B8", "B11", "B12"]) .addBands(ndvi) .addBands(s1_composite.select(["VV", "VH"])))print("Feature stack bands:", ml_stack.bandNames().getInfo())6.2 Sample labelled points and train a classifier (preview of Day 2)The points below are illustrative only (a few forest points in the Puerto Princesa Subterranean River area and open-water points in the Sulu Sea). On Day 2 you will use a proper labelled dataset, many more samples and an independent validation set.
forest = [[118.90, 10.15], [118.93, 10.12], [118.86, 10.10], [118.88, 10.05]]water = [[119.00, 9.60], [118.95, 9.55], [118.98, 9.70]]pts = ee.FeatureCollection( [ee.Feature(ee.Geometry.Point(p), {"landcover": 0}) for p in forest] + [ee.Feature(ee.Geometry.Point(p), {"landcover": 1}) for p in water])training = ml_stack.sampleRegions(collection=pts, properties=["landcover"], scale=10)print("Training samples:", training.size().getInfo())classifier = ee.Classifier.smileRandomForest(numberOfTrees=50, seed=42).train( features=training, classProperty="landcover", inputProperties=ml_stack.bandNames())classified = ml_stack.classify(classifier)display(Image(url=classified.getThumbURL({"region": aoi, "dimensions": 512, "min": 0, "max": 1, "palette": ["darkgreen", "blue"]})))With only two classes and seven points, everything on land is labelled “forest” — a good reminder that a model is only as good as its training data (Session 2: data-centric AI).
—## 7. Best PracticesEfficiency- Filter early (bounds → date → metadata), select only the bands you need, clip at the end- Choose a sensible scale for statistics; use .limit(n) while testing- Use .getInfo() only for small results; export everything largeQuotas- Non-commercial Cloud projects have usage quotas (compute, concurrent requests and exports). Check the current limits in the Earth Engine documentation (“Usage and quotas”) if tasks are throttled.GEE or local?| Earth Engine | Local / Colab (Python, GPU) ||—|—|| Data access, cloud masking, compositing | Deep learning (CNN, U-Net, LSTM) || Large-area statistics and time series | Custom architectures, augmentation, transfer learning || Random Forest / CART prototypes | Full control of training and evaluation |Typical workflow: prepare data in GEE → export → train in Colab/locally → apply to new data.Common errors| Error | Fix ||—|—|| User memory limit exceeded | Smaller region or coarser scale; export instead of getInfo() || Computation timed out | Simplify, filter more, split into smaller exports || Collection.first: No matching elements | No images for your filters: check dates, AOI, cloud filter || Image.select: Pattern 'X' did not match any bands | Check image.bandNames().getInfo() || Export fails | Increase maxPixels, check Drive space and region |
—## Recap- Setup: ee.Authenticate() once, ee.Initialize(project=...) every session- Objects: Geometry, Image, ImageCollection, Feature, FeatureCollection; computation is lazy- Sentinel-2: S2_SR_HARMONIZED + Cloud Score+ masking + median composite → NDVI- Sentinel-1: S1_GRD in dB, filter by mode/polarisation/orbit; ratios in dB are differences- Exports: images and tables to Drive in a projected CRS, for ML outside GEE- ML preview: feature stacks + sampleRegions + smileRandomForest## Next: Day 2 — Machine Learning for land coverRandom Forest classification of Palawan land cover: training data design, feature engineering, validation and accuracy assessment.## Optional practice- A. Dry vs wet season NDVI difference for the same AOI- B. Compare mean NDVI of an urban, a farming and a forest AOI- C. Flood candidates: pixels with VV < −18 dB in a typhoon month that were brighter in the dry season- D. NDVI time series for one point over 2024 (ui.Chart is JS-only; in Python use getRegion or geemap)## Resources- Earth Engine guides: https://developers.google.com/earth-engine/guides · Python API: https://developers.google.com/earth-engine/guides/python_install- Data catalog: https://developers.google.com/earth-engine/datasets · Cloud Score+: https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_CLOUD_SCORE_PLUS_V1_S2_HARMONIZED- End-to-End GEE course (Spatial Thoughts): https://courses.spatialthoughts.com/end-to-end-gee.html- Cloud-Based Remote Sensing with Google Earth Engine (Cardille et al., open access): https://www.eefabook.org/- Philippine Copernicus data: CopPhil Infrastructure https://infra.copphil.philsa.gov.ph · PhilSA https://philsa.gov.ph/—EO AI/ML Training · Dimitrios Kasampalis (Anefelo) · CC BY-SA 4.0