Create a flood inundation mapping from SAR with validation.
- User
Create a flood inundation mapping from SAR with validation.
Assistant
Create a flood inundation mapping from SAR with validation.
1. Analyze the Request: * Goal: Create a flood inundation map using Synthetic Aperture Radar (SAR) data. * Requirement: Include validation of the results. * Format: The user likely wants a guide, workflow, or code example (Python) demonstrating this process.
Target Audience: Likely a GIS professional, remote sensing student, or researcher. They probably have some familiarity with Python and Earth Engine (GEE) or similar platforms. I should provide a comprehensive workflow that is practical and reproducible.
Key Components of the Workflow:
Tool Selection: Google Earth Engine (GEE) is the best tool for this because:
geemap is more portable and "professional" looking for a "Create a..." prompt. I will provide a Python/GEE approach using geemap.Drafting the Workflow (Mental Outline):
ee, geemap).Post - Pre.Refining the Code Structure (Python/Geemap):
import ee, import geemap.mask_s2_clouds: For validation data.otsu: Helper function for thresholding.ee.Reducer.contingency.Adding Explanations: The code alone is insufficient. I need to explain why we do each step (SAR interaction with water, speckle, slopes).
Self-Correction/Critique during drafting:
focal_median for simplicity in code, though specialized filters exist.Finalizing the Output Structure:
Writing the Content: (Drafting the code blocks - ensuring GEE syntax is correct for Python API).
collection.filterDate(...).mosaic().focal_mean(...)errorMatrix in GEE.Review against User Prompt:
This thought process moves from understanding requirements to tool selection, technical drafting, handling edge cases (clouds/noise), and structuring the final deliverable for clarity. The inclusion of the geemap library makes the code interactive and visual, which is high value.
(Self-Correction during code generation): Make sure to handle the date filtering carefully. We need a "Pre-flood" (baseline) and "Post-flood" image.
(Post < Threshold) AND (Post < Pre - Buffer) is a common logic to isolate new water. Let's stick to a simpler but effective Otsu on the post-flood image, then mask permanent water using JRC Pekel layer. That's more robust for a tutorial.Wait, the prompt asks for "Validation". If I use JRC Pekel to mask, I can't use it to validate (circular logic). Therefore, for validation, I must use Sentinel-2 (Optical). I will define the AOI where S2 is likely clear (or try multiple dates).
Let's refine the Validation Code:
This looks solid. Proceed with generating the response. This is a comprehensive guide and Python workflow to create a Flood Inundation Map using Sentinel-1 SAR data and validate it using Sentinel-2 Optical data.
We will use Google Earth Engine (GEE) via the Python API (geemap library) because it handles the heavy data processing and projection matching automatically.
pip install earthengine-api geemap geopandas
Save the following code as flood_mapping.py or run it in a Jupyter Notebook.
The script prints a Confusion Matrix. In a perfect scenario, if SAR correctly identified water where Optical imagery also sees water, the numbers should align.
focal_median) to smooth this out. Without it, you will get a "salt and pepper" noise in your flood map.import ee
import geemap
import os
# -----------------------------------------------------------------------------
# 1. Initialization
# -----------------------------------------------------------------------------
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
# Define Area of Interest (ROI)
# Example: A region prone to flooding. Coordinates [West, South, East, North]
# You can also load a shapefile: roi = geemap.shp_to_ee('path_to_shapefile.shp')
roi = ee.Geometry.Rectangle([89.5, 25.0, 90.0, 25.5]) # Example: Bangladesh
# Define Dates (Ensure Sentinel-2 data is available for validation date)
flood_date = '2022-06-20'
pre_flood_date = '2022-06-01' # Used for reference if doing change detection
validation_date = '2022-06-20' # Ideally same day or very close
print("Initializing Flood Mapping Workflow...")
# -----------------------------------------------------------------------------
# 2. Sentinel-1 (SAR) Processing
# -----------------------------------------------------------------------------
def get_s1_collection(date, roi):
# Load Sentinel-1 GRD data
s1 = (ee.ImageCollection('COPERNICUS/S1_GRD')
.filterBounds(roi)
.filterDate(ee.Date(date), ee.Date(date).advance(5, 'day'))
.filter(ee.Filter.eq('instrumentMode', 'IW'))
.filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING'))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))
.select('VV')
.mosaic() # Merge images in time window
.clip(roi))
# Apply Speckle Filter (Lee Sigma)
s1_filtered = ee.Image(s1).focal_median(radius=50, units='meters').rename('VV_filtered')
return s1_filtered
# Get SAR image
s1_img = get_s1_collection(flood_date, roi)
# Otsu Thresholding Algorithm (Automatic threshold detection)
def otsu_function(histogram):
counts = ee.Array(ee.Dictionary(histogram).get('histogram'))
means = ee.Array(ee.Dictionary(histogram).get('bucketMeans'))
size = means.length().get([0])
total = counts.reduce(ee.Reducer.sum(), [0]).get([0])
sum_ = means.multiply(counts).reduce(ee.Reducer.sum(), [0]).get([0])
mean = sum_.divide(total)
indices = ee.List.sequence(1, size)
# Compute between class variance
def compute_bss(i):
aCounts = counts.slice(0, 0, i)
aCount = aCounts.reduce(ee.Reducer.sum(), [0]).get([0])
aMeans = means.slice(0, 0, i)
aMean = aMeans.multiply(aCounts).reduce(ee.Reducer.sum(), [0]).divide(aCount).get([0])
bCount = total.subtract(aCount)
bMean = sum_.subtract(aCount.multiply(aMean)).divide(bCount)
return aCount.multiply(aMean.subtract(mean).pow(2)).add(
bCount.multiply(bMean.subtract(mean).pow(2)))
bss = indices.map(compute_bss)
return means.sort(bss).get([-1])
# Calculate Threshold
histogram_dict = s1_img.reduceRegion(
reducer=ee.Reducer.histogram().combine('mean', None, True).combine('variance', None, True),
geometry=roi,
scale=30,
bestEffort=True
)
threshold = otsu_function(histogram_dict.get('VV_filtered_histogram'))
print(f"Calculated SAR Threshold (dB): {threshold.getInfo()}")
# Create Water Mask (Values below threshold are water)
sar_water_mask = s1_img.lt(threshold).rename('water_sar')
# Mask out permanent water (Optional: Using JRC Global Surface Water)
# Here we keep it simple: 1 = Flood Water, 0 = Non-Water
# -----------------------------------------------------------------------------
# 3. Validation (Sentinel-2 Optical) Processing
# -----------------------------------------------------------------------------
def get_s2_collection(date, roi):
# Load Sentinel-2
s2 = (ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
.filterBounds(roi)
.filterDate(ee.Date(date), ee.Date(date).advance(10, 'day')) # Wider window for optical due to clouds
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
.mosaic()
.clip(roi))
# Cloud Masking using QA60 band
qa = s2.select('QA60')
cloud_bit_mask = 1 << 10
cirrus_bit_mask = 1 << 11
mask = qa.bitwiseAnd(cloud_bit_mask).eq(0).And(qa.bitwiseAnd(cirrus_bit_mask).eq(0))
s2_masked = s2.updateMask(mask)
return s2_masked
s2_img = get_s2_collection(validation_date, roi)
# Calculate MNDWI (Modified Normalized Difference Water Index)
# MNDWI = (Green - SWIR) / (Green + SWIR)
# Green = B3, SWIR = B11
mndwi = s2_img.normalizedDifference(['B3', 'B11']).rename('MNDWI')
# Threshold for MNDWI (Standard is > 0 for water)
# We use a fixed threshold here for simplicity, though Otsu could be used here too
optical_water_mask = mndwi.gt(0).rename('water_optical')
# -----------------------------------------------------------------------------
# 4. Validation Analysis (Confusion Matrix)
# -----------------------------------------------------------------------------
# To compare, we need to reproject one image to match the other exactly.
# Let's resample Optical to SAR resolution (10m -> 30m approx)
optical_resampled = optical_water_mask.reproject(crs=sar_water_mask.projection())
# Rename bands for clarity
sar_map = sar_water_mask.rename('classification')
val_map = optical_resampled.rename('validation')
# Sample points for accuracy assessment
sample_points = ee.Image.random().multiply(1000).int().sample(
region=roi,
scale=30,
numPixels=1000,
geometries=True
)
# Extract values to points
training_data = ee.Image.cat([sar_map, val_map]).sampleRegions(
collection=sample_points,
properties=[],
scale=30
)
# Calculate Confusion Matrix
# 0 = Non-water, 1 = Water
cm = training_data.errorMatrix('classification', 'validation')
print("\n--- Validation Results ---")
print("Confusion Matrix (0: Non-Water, 1: Water):")
print(cm.getInfo())
print(f"Overall Accuracy: {cm.accuracy().getInfo():.2f}")
print(f"Kappa Coefficient: {cm.kappa().getInfo():.2f}")
# -----------------------------------------------------------------------------
# 5. Visualization & Export
# -----------------------------------------------------------------------------
Map = geemap.Map()
Map.centerObject(roi, 10)
# Visualization Parameters
sar_vis = {'min': -25, 'max': 5, 'palette': ['black', 'white']}
water_vis = {'palette': ['white', 'blue']}
mndwi_vis = {'min': -1, 'max': 1, 'palette': ['red', 'white', 'blue']}
# Add Layers
Map.addLayer(s1_img, sar_vis, 'Sentinel-1 SAR (VV)', True)
Map.addLayer(sar_water_mask.selfMask(), {'palette': 'red'}, 'SAR Flood Map', True)
Map.addLayer(mndwi, mndwi_vis, 'Sentinel-2 MNDWI', False)
Map.addLayer(optical_water_mask.selfMask(), {'palette': 'cyan'}, 'Optical Water Map (Val)', True)
print("Displaying Map...")
Map
# Optional: Export to Drive
# geemap.ee_export_image_to_drive(sar_water_mask, description='Flood_Map', scale=30, region=roi)