# Getting Started¶

In this tutorial, we demonstrate some of the basic features of TorchGeo and show how easy it is to use if you’re already familiar with other PyTorch domain libraries like torchvision.

It’s recommended to run this notebook on Google Colab if you don’t have your own GPU. Click the “Open in Colab” button above to get started.

## Setup¶

First, we install TorchGeo.

[1]:

%pip install torchgeo


## Imports¶

Next, we import TorchGeo and any other libraries we need.

[2]:

import os
import tempfile

from torch.utils.data import DataLoader

from torchgeo.datasets import NAIP, ChesapeakeDE, stack_samples
from torchgeo.samplers import RandomGeoSampler


## Datasets¶

For this tutorial, we’ll be using imagery from the National Agriculture Imagery Program (NAIP) and labels from the Chesapeake Bay High-Resolution Land Cover Project. First, we manually download a few NAIP tiles and create a PyTorch Dataset.

[3]:

data_root = tempfile.gettempdir()
naip_root = os.path.join(data_root, "naip")
naip_url = (
"https://naipeuwest.blob.core.windows.net/naip/v002/de/2018/de_060cm_2018/38075/"
)
tiles = [
"m_3807511_ne_18_060_20181104.tif",
"m_3807511_se_18_060_20181104.tif",
"m_3807512_nw_18_060_20180815.tif",
"m_3807512_sw_18_060_20180815.tif",
]
for tile in tiles:

naip = NAIP(naip_root)

Downloading https://naipeuwest.blob.core.windows.net/naip/v002/de/2018/de_060cm_2018/38075/m_3807511_ne_18_060_20181104.tif to data/naip/m_3807511_ne_18_060_20181104.tif

Downloading https://naipeuwest.blob.core.windows.net/naip/v002/de/2018/de_060cm_2018/38075/m_3807511_se_18_060_20181104.tif to data/naip/m_3807511_se_18_060_20181104.tif

Downloading https://naipeuwest.blob.core.windows.net/naip/v002/de/2018/de_060cm_2018/38075/m_3807512_nw_18_060_20180815.tif to data/naip/m_3807512_nw_18_060_20180815.tif

Downloading https://naipeuwest.blob.core.windows.net/naip/v002/de/2018/de_060cm_2018/38075/m_3807512_sw_18_060_20180815.tif to data/naip/m_3807512_sw_18_060_20180815.tif


Next, we tell TorchGeo to automatically download the corresponding Chesapeake labels.

[4]:

chesapeake_root = os.path.join(data_root, "chesapeake")


Files already downloaded and verified


Finally, we create an IntersectionDataset so that we can automatically sample from both GeoDatasets simultaneously.

[5]:

dataset = naip & chesapeake


## Sampler¶

Unlike typical PyTorch Datasets, TorchGeo GeoDatasets are indexed using lat/long/time bounding boxes. This requires us to use a custom GeoSampler instead of the default sampler/batch_sampler that comes with PyTorch.

[6]:

sampler = RandomGeoSampler(dataset, size=1000, length=10)


Now that we have a Dataset and Sampler, we can combine these into a single DataLoader.

[7]:

dataloader = DataLoader(dataset, sampler=sampler, collate_fn=stack_samples)


## Training¶

Other than that, the rest of the training pipeline is the same as it is for torchvision.

[8]:

for sample in dataloader:
image = sample["image"]