惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
月光博客
月光博客
博客园 - 司徒正美
爱范儿
爱范儿
aimingoo的专栏
aimingoo的专栏
量子位
Recent Announcements
Recent Announcements
V
V2EX
P
Proofpoint News Feed
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
宝玉的分享
宝玉的分享
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
B
Blog
博客园_首页
GbyAI
GbyAI
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Getting Started with TorchGeo — Remote Sensing with PyTorch
gezi-wen · 2026-05-22 · via DEV Community

gezi-wen

torchvision is great for natural images. But remote sensing data is different:

  • GeoTIFFs, not PNGs — with coordinate reference systems baked in
  • Multi-spectral bands — beyond RGB into near-infrared, thermal, SAR
  • Massive sizes — a single satellite image can be 10,000×10,000 pixels
  • Spatial context matters — random cropping destroys geographic patterns

TorchGeo is PyTorch's official geospatial extension by Microsoft. It provides 50+ remote sensing datasets (one-line download), geo-aware samplers, and seamless integration with torchvision and PyTorch Lightning.

pip install torchgeo rasterio

Enter fullscreen mode Exit fullscreen mode


Loading Your First Dataset

Let's start with EuroSAT — 27,000 Sentinel-2 satellite images across 10 land cover classes:

from torchgeo.datasets import EuroSAT

dataset = EuroSAT(root="./data", download=True)
print(len(dataset))          # 27000
print(dataset.num_classes)   # 10
print(dataset.classes)
# ['AnnualCrop', 'Forest', 'HerbaceousVegetation',
#  'Highway', 'Industrial', 'Pasture', 'PermanentCrop',
#  'Residential', 'River', 'SeaLake']

Enter fullscreen mode Exit fullscreen mode

Each sample is a dict with image (multi-spectral tensor) and label (integer):

sample = dataset[0]
print(sample['image'].shape)  # torch.Size([13, 64, 64]) — 13 Sentinel-2 bands
print(sample['label'])        # 0 → AnnualCrop

Enter fullscreen mode Exit fullscreen mode


Building the Data Pipeline

Remote sensing datasets return dicts, so we need a custom collate_fn:

from torch.utils.data import DataLoader
from torchvision import transforms

transform = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.Lambda(lambda x: x.float() / 255.0),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225])
])

def collate_fn(batch):
    images = torch.stack([transform(b['image'][:3]) for b in batch])
    labels = torch.tensor([b['label'] for b in batch])
    return images, labels

loader = DataLoader(dataset, batch_size=32, collate_fn=collate_fn)

Enter fullscreen mode Exit fullscreen mode

For RGB display, we take image[:3] (B04, B03, B02). For multi-spectral analysis, keep all 13 bands.


Transfer Learning with ResNet18

Replace the final fully-connected layer for our 10 classes:

from torchvision.models import resnet18
import torch.nn as nn

model = resnet18(weights='IMAGENET1K_V1')
model.fc = nn.Linear(512, 10)

Enter fullscreen mode Exit fullscreen mode

With 3 epochs and ImageNet pretrained weights on GPU (RTX 4060, 8GB), this reaches 97.8% training accuracy and 83.7% test accuracy in just 40 seconds:

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

for epoch in range(3):
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

Enter fullscreen mode Exit fullscreen mode


Key Datasets at a Glance

Dataset Task Size Classes
RESISC45 Scene classification 31,500 45
UCMerced Land use 2,100 21
LandCoverAI Land cover 10,674 5
BigEarthNet Multi-label 590k 43

Where to Go Next

  1. Geo-aware samplingRandomGeoSampler for tiling massive GeoTIFFs
  2. Pre-trained remote sensing models — TorchGeo ships weights pretrained on BigEarthNet
  3. Semantic segmentationLandCoverAI + DeepLabV3 for pixel-level classification
  4. Multi-spectral processing — Work with all 13 Sentinel-2 bands
  5. Change detection — Compare satellite images across time

Official docs: docs.torchgeo.org


References