Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add plotting method for CV4A Kenya Crop Type Dataset #312

Merged
merged 5 commits into from
Dec 29, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion tests/datasets/test_cv4a_kenya_crop_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
from pathlib import Path
from typing import Generator

import matplotlib.pyplot as plt
import pytest
import torch
import torch.nn as nn
from _pytest.fixtures import SubRequest
from _pytest.monkeypatch import MonkeyPatch
from torch.utils.data import ConcatDataset

Expand All @@ -32,7 +34,10 @@ def fetch(dataset_id: str, **kwargs: str) -> Dataset:
class TestCV4AKenyaCropType:
@pytest.fixture
def dataset(
self, monkeypatch: Generator[MonkeyPatch, None, None], tmp_path: Path
self,
monkeypatch: Generator[MonkeyPatch, None, None],
tmp_path: Path,
request: SubRequest,
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved
) -> CV4AKenyaCropType:
radiant_mlhub = pytest.importorskip("radiant_mlhub", minversion="0.2.1")
monkeypatch.setattr( # type: ignore[attr-defined]
Expand All @@ -53,6 +58,7 @@ def dataset(
CV4AKenyaCropType, "dates", ["20190606"]
)
root = str(tmp_path)
self.root = root
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved
transforms = nn.Identity() # type: ignore[attr-defined]
return CV4AKenyaCropType(
root,
Expand Down Expand Up @@ -113,3 +119,17 @@ def test_invalid_bands(self) -> None:

with pytest.raises(ValueError, match="is an invalid band name."):
CV4AKenyaCropType(bands=("foo", "bar"))

def test_plot(self, dataset: CV4AKenyaCropType) -> None:
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved
dataset.plot(dataset[0], time_step=0, suptitle="Test")
plt.close()

sample = dataset[0]
sample["prediction"] = sample["mask"].clone()
dataset.plot(sample, time_step=0, suptitle="Pred")
plt.close()

def test_plot_rgb(self, dataset: CV4AKenyaCropType) -> None:
dataset = CV4AKenyaCropType(root=dataset.root, bands=tuple(["B01"]))
with pytest.raises(ValueError, match="doesn't contain some of the RGB bands"):
dataset.plot(dataset[0], time_step=0, suptitle="Single Band")
68 changes: 68 additions & 0 deletions torchgeo/datasets/cv4a_kenya_crop_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Tuple

import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
Expand Down Expand Up @@ -102,6 +103,8 @@ class CV4AKenyaCropType(VisionDataset):
"CLD",
)

RGB_BANDS = ["B04", "B03", "B02"]

# Same for all tiles
tile_height = 3035
tile_width = 2016
Expand Down Expand Up @@ -400,3 +403,68 @@ def _download(self, api_key: Optional[str] = None) -> None:
target_archive_path = os.path.join(self.root, self.target_meta["filename"])
for fn in [image_archive_path, target_archive_path]:
extract_archive(fn, self.root)

def plot(
self,
sample: Dict[str, Tensor],
show_titles: bool = True,
time_step: int = 0,
suptitle: Optional[str] = None,
) -> plt.Figure:
"""Plot a sample from the dataset.

Args:
sample: a sample return by :meth:`__getitem__`
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved
show_titles: flag indicating whether to show titles above each panel
time_step: time step at which to access image, beginning with 0
suptitle: optional suptitle to use for figure

Returns:
a matplotlib Figure with the rendered sample

.. versionadded:: 0.2
"""
rgb_indices = []
for band in self.RGB_BANDS:
if band in self.bands:
rgb_indices.append(self.bands.index(band))
else:
raise ValueError("Dataset doesn't contain some of the RGB bands")

if "prediction" in sample:
prediction = sample["prediction"]
n_cols = 3
else:
n_cols = 2

image, mask = sample["image"], sample["mask"]

assert time_step <= image.shape[0] - 1, (
"The specified time step"
" does not exist, image only contains {} time"
" instances."
).format(image.shape[0])

image = image[time_step, rgb_indices, :, :]

fig, axs = plt.subplots(nrows=1, ncols=n_cols, figsize=(10, n_cols * 5))

axs[0].imshow(image.permute(1, 2, 0))
axs[0].axis("off")
axs[1].imshow(mask)
axs[1].axis("off")

if "prediction" in sample:
axs[2].imshow(prediction)
axs[2].axis("off")
if show_titles:
axs[2].set_title("Prediction")

if show_titles:
axs[0].set_title("Image")
axs[1].set_title("Mask")

if suptitle is not None:
plt.suptitle(suptitle)

return fig