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 own plot method to CMSMangroveCanopy #427

Merged
merged 6 commits into from
Feb 26, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 7 additions & 1 deletion tests/datasets/test_cms_mangrove_canopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,10 @@ def test_or(self, dataset: CMSGlobalMangroveCanopy) -> None:
def test_plot(self, dataset: CMSGlobalMangroveCanopy) -> None:
query = dataset.bounds
x = dataset[query]
dataset.plot(x["mask"])
dataset.plot(x, suptitle="Test")

def test_plot_prediction(self, dataset: CMSGlobalMangroveCanopy) -> None:
query = dataset.bounds
x = dataset[query]
x["prediction"] = x["mask"].clone()
dataset.plot(x, suptitle="Prediction")
47 changes: 47 additions & 0 deletions torchgeo/datasets/cms_mangrove_canopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import os
from typing import Any, Callable, Dict, Optional

import matplotlib.pyplot as plt
from rasterio.crs import CRS
from torch import Tensor

from .geo import RasterDataset
from .utils import check_integrity, extract_archive
Expand Down Expand Up @@ -249,3 +251,48 @@ def _extract(self) -> None:
"""Extract the dataset."""
pathname = os.path.join(self.root, self.zipfile)
extract_archive(pathname)

def plot( # type: ignore[override]
self,
sample: Dict[str, Tensor],
calebrob6 marked this conversation as resolved.
Show resolved Hide resolved
show_titles: bool = True,
suptitle: Optional[str] = None,
) -> plt.Figure:
"""Plot a sample from the dataset.

Args:
sample: a sample returned by :meth:`RasterDataset.__getitem__`
show_titles: flag indicating whether to show titles above each panel
suptitle: optional string to use as a suptitle

Returns:
a matplotlib Figure with the rendered sample
"""
calebrob6 marked this conversation as resolved.
Show resolved Hide resolved
mask = sample["mask"].squeeze()
ncols = 1

showing_predictions = "prediction" in sample
if showing_predictions:
pred = sample["prediction"].squeeze()
ncols = 2

fig, axs = plt.subplots(nrows=1, ncols=ncols, figsize=(ncols * 4, 4))

if showing_predictions:
axs[0].imshow(mask)
axs[0].axis("off")
axs[1].imshow(pred)
axs[1].axis("off")
if show_titles:
axs[0].set_title("Mask")
axs[1].set_title("Prediction")
else:
axs.imshow(mask)
axs.axis("off")
if show_titles:
axs.set_title("Mask")

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

return