Using AI in Geospatial Analysis for Humanitarian Applications

Shahzad Asghar
6 min readNov 13, 2024

--

In humanitarian operations, combining AI with geospatial analysis has become a game-changer, enhancing how we respond to complex crises. Here’s a breakdown of practical uses and examples showing how AI and geospatial tools can significantly impact on-the-ground decisions in crisis situations.

1. Extracting Key Information from Text Data

Humanitarian operations generate vast amounts of data in unstructured formats — field reports, social media posts, local news snippets, and feedback from people in affected areas. Manually sorting through these sources can be time-consuming, so large language models (LLMs) come in handy to extract actionable insights rapidly.

For example, when managing a disaster response, it’s essential to know which areas are hardest hit and what resources are urgently needed. LLMs can analyze text from reports, pull out place names, and extract specific needs (like food or shelter), all of which can be mapped to guide the allocation of resources.

# Extracting location and needs from report text
import openai
openai.api_key = "your_api_key"
response = openai.Completion.create(
model="gpt-4i",
prompt="Extract location, severity, and needs from: 'Flooding in Area A displaced 1,500 people. Urgent need for medical aid and food supplies.'",
max_tokens=100
)
print(response['choices'][0]['text'])

2. Remote Damage Assessment Using Satellite Imagery

Satellite imagery is a powerful tool in assessing disaster damage when ground access is limited. AI models trained to analyze these images can classify and assess damage levels across affected areas, providing remote teams with vital information without needing immediate on-the-ground inspections.

For example, after a storm, AI models analyze satellite images and tag locations by the level of damage, which can then be integrated into a GIS (Geographic Information System) to layer over population data and identify regions where the response is most needed.

# Using a pretrained model to classify damage in satellite imagery
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
model = load_model('damage_model.h5')
img = Image.open('satellite_image.jpg').resize((224, 224))
img_array = np.array(img) / 255.0
img_array = img_array.reshape((1, 224, 224, 3))
damage_level = model.predict(img_array)
print("Damage Level:", damage_level)

3. Predicting Resource Needs Using Machine Learning

Predictive analytics allows for better planning in terms of resource distribution. For example, forecasting the demand for shelter based on incoming population data, or predicting water and food needs, can help pre-position supplies in areas likely to see high demand. This approach combines past data, AI, and current indicators for targeted forecasting.

The example below uses basic regression to estimate the shelter requirements for various camps, adjusting automatically based on new data.

import pandas as pd
from sklearn.linear_model import LinearRegression
data = pd.DataFrame({
'Region': ['Location A', 'Location B', 'Location C'],
'Population': [2000, 1500, 3000],
'Shelters': [400, 250, 500]
})
X = data[['Population']]
y = data['Shelters']
model = LinearRegression().fit(X, y)
new_data = pd.DataFrame({'Population': [2200, 1600, 3500]})
predictions = model.predict(new_data)
print("Predicted Shelter Needs:", predictions)

4. Real-Time Monitoring with Heatmaps

Heatmaps are invaluable for real-time tracking of resources and needs across different regions. By integrating live data with geospatial tools, teams can gain a real-time snapshot of conditions, highlighting areas with gaps in resources or emerging needs. Visualizing this data through heatmaps offers an instant view of high-priority locations, making resource allocation and support much more efficient.

import folium
from folium.plugins import HeatMap
data = [
[32.0, 36.5, 0.5], # Latitude, Longitude, Intensity
[31.7, 36.0, 0.7],
[31.9, 36.2, 0.6]
]
m = folium.Map(location=[31.7, 36.2], zoom_start=7)
HeatMap(data).add_to(m)
m.save("heatmap.html")

2. Mapping and Clustering of Affected Areas Using Satellite Data

One useful approach for spatial analysis is mapping areas affected by disasters and clustering them based on damage intensity. Let’s dive into a more complex example where satellite data is used to identify and cluster affected areas based on damage levels.

Assume you have pre-processed satellite imagery data for an area affected by a natural disaster, where each pixel in the image is labeled with a damage level. Here, we’ll cluster these points based on location and damage level, giving priority to areas with higher damage intensity.

Code Implementation

We’ll use Python with scikit-learn, PIL (for image processing), and matplotlib for visualization.

import numpy as np
from PIL import Image
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
# Step 1: Load pre-processed satellite image as a numpy array
# Assume the image is grayscale, with pixel intensity indicating damage level
# (e.g., 0 for no damage, 255 for maximum damage)
img = Image.open('satellite_damage_image.jpg').convert('L')
img_data = np.array(img)
# Step 2: Threshold the image to identify damaged areas (intensity > threshold)
damage_threshold = 100
damaged_pixels = np.argwhere(img_data > damage_threshold)
# Step 3: Cluster damaged areas using DBSCAN to group nearby points
# DBSCAN parameters can be tuned based on desired clustering size
db = DBSCAN(eps=10, min_samples=5).fit(damaged_pixels)
labels = db.labels_
# Step 4: Visualize the clusters
plt.figure(figsize=(10, 10))
unique_labels = set(labels)
for label in unique_labels:
if label == -1: # -1 label is for noise points in DBSCAN
color = 'gray'
label_text = 'Noise'
else:
color = plt.cm.Spectral(float(label) / len(unique_labels))
label_text = f'Cluster {label}'
cluster_points = damaged_pixels[labels == label]
plt.scatter(cluster_points[:, 1], cluster_points[:, 0], c=[color], label=label_text)
plt.gca().invert_yaxis()
plt.title("Clusters of Damaged Areas")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.legend(loc="upper right")
plt.show()

In this example:

  • DBSCAN groups nearby damaged pixels, making it easy to visualize clusters of severe damage.
  • You can adjust eps and min_samples in DBSCAN to control how closely pixels need to be grouped to count as part of the same cluster.

2. Heatmap Analysis with Interpolation for Predictive Resource Allocation

After clustering, you might need a continuous heatmap to indicate damage intensity over an entire region, including areas without direct data points. This can be achieved with spatial interpolation (using Kriging or Gaussian Process Regression), providing a predictive surface that helps prioritize resource allocation.

Let’s use scipy for interpolation and visualize the result with matplotlib.

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Step 1: Simulate some example data from damaged areas
# Sample latitude, longitude, and damage intensity
coords = np.array([
[31.95, 35.93, 0.7],
[31.96, 35.92, 0.9],
[31.94, 35.91, 0.8],
[31.97, 35.95, 0.5]
])
latitudes = coords[:, 0]
longitudes = coords[:, 1]
intensities = coords[:, 2]
# Step 2: Define a grid for interpolation
grid_lat, grid_lon = np.mgrid[31.9:32.0:100j, 35.9:36.0:100j]
# Step 3: Perform grid interpolation
grid_z = griddata((latitudes, longitudes), intensities, (grid_lat, grid_lon), method='cubic')
# Step 4: Plot the interpolated heatmap
plt.figure(figsize=(8, 8))
plt.imshow(grid_z.T, extent=(35.9, 36.0, 31.9, 32.0), origin='lower', cmap='hot', alpha=0.6)
plt.colorbar(label='Damage Intensity')
plt.scatter(longitudes, latitudes, c=intensities, s=100, edgecolor='k', label='Sample Points')
plt.title('Interpolated Heatmap of Damage Intensity')
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.legend()
plt.show()

In this code:

  • Grid Interpolation fills in gaps between sample points, creating a heatmap for the entire area.
  • Griddata is used here with cubic interpolation to create a smooth surface over the grid.

This visualization helps prioritize regions with higher predicted intensity even where direct damage data might be sparse, improving resource distribution.

3. Time-Series Geospatial Analysis for Monitoring Changes

Tracking changes in affected areas over time is essential in dynamic humanitarian responses. This example calculates the change in damage intensity across several satellite images taken over consecutive days.

Here’s how to compute and visualize the differences:

# Step 1: Load consecutive satellite images (as grayscale)
img_day1 = np.array(Image.open('satellite_image_day1.jpg').convert('L'))
img_day2 = np.array(Image.open('satellite_image_day2.jpg').convert('L'))
# Step 2: Calculate change in intensity (positive values mean increased damage)
intensity_change = img_day2 - img_day1
# Step 3: Threshold the difference to highlight significant changes
change_threshold = 30
significant_change = np.where(np.abs(intensity_change) > change_threshold, intensity_change, 0)
# Step 4: Visualize change over time
plt.figure(figsize=(10, 10))
plt.imshow(significant_change, cmap='coolwarm', interpolation='nearest')
plt.colorbar(label='Change in Damage Intensity')
plt.title("Change in Damage Intensity Between Days")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.show()

In this time-series analysis:

  • Intensity Change Calculation reveals areas where damage has increased or decreased.
  • Using a threshold highlights only significant changes, allowing teams to focus on worsening areas or areas recovering faster.

Summary

These examples demonstrate advanced spatial analysis techniques with real-world applications in humanitarian response:

  1. Clustering to identify and prioritize damage.
  2. Heatmap Interpolation to predict resource needs in less-assessed areas.
  3. Time-Series Analysis to monitor changes and adapt response efforts.

Feel free to adapt the parameters to match your data or specific operational needs. Or ping me for full working git.

--

--

No responses yet