Skip to content

Generic Datasets#

terratorch.datasets.generic_pixel_wise_dataset.GenericNonGeoSegmentationDataset #

Bases: GenericPixelWiseDataset

GenericNonGeoSegmentationDataset

Source code in terratorch/datasets/generic_pixel_wise_dataset.py
class GenericNonGeoSegmentationDataset(GenericPixelWiseDataset):
    """GenericNonGeoSegmentationDataset"""

    def __init__(
        self,
        data_root: Path,
        num_classes: int,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        ignore_split_file_extensions: bool = True,
        allow_substring_split_file: bool = True,
        rgb_indices: list[str] | None = None,
        dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        class_names: list[str] | None = None,
        constant_scale: float = 1,
        transform: A.Compose | None = None,
        no_data_replace: float | None = None,
        no_label_replace: int | None = None,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
    ) -> None:
        """Constructor

        Args:
            data_root (Path): Path to data root directory
            num_classes (int): Number of classes in the dataset
            label_data_root (Path, optional): Path to data root directory with labels.
                If not specified, will use the same as for images.
            image_grep (str, optional): Regular expression appended to data_root to find input images.
                Defaults to "*".
            label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
                Defaults to "*".
            split (Path, optional): Path to file containing files to be used for this split.
                The file should be a new-line separated prefixes contained in the desired files.
                Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
            ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
                file to determine which files to include in the dataset.
                E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
                actually ".jpg". Defaults to True
            allow_substring_split_file (bool, optional): Whether the split files contain substrings
                that must be present in file names to be included (as in mmsegmentation), or exact
                matches (e.g. eurosat). Defaults to True.
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
            output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
            class_names (list[str], optional): Class names. Defaults to None.
            constant_scale (float): Factor to multiply image values by. Defaults to 1.
            transform (Albumentations.Compose | None): Albumentations transform to be applied.
                Should end with ToTensorV2(). If used through the generic_data_module,
                should not include normalization. Not supported for multi-temporal data.
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
            no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to None.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
        """
        super().__init__(
            data_root,
            label_data_root=label_data_root,
            image_grep=image_grep,
            label_grep=label_grep,
            split=split,
            ignore_split_file_extensions=ignore_split_file_extensions,
            allow_substring_split_file=allow_substring_split_file,
            rgb_indices=rgb_indices,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            no_label_replace=no_label_replace,
            expand_temporal_dimension=expand_temporal_dimension,
            reduce_zero_label=reduce_zero_label,
        )
        self.num_classes = num_classes
        self.class_names = class_names

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)
        if "mask" in item:
            item["mask"] = item["mask"].long()
        return item

    def plot(self, sample: dict[str, Tensor], suptitle: str | None = None, show_axes: bool | None = False) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample: a sample returned by :meth:`__getitem__`
            suptitle: optional string to use as a suptitle
            show_axes: whether to show axes or not

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """
        image = sample["image"]
        if len(image.shape) == 5:
            return
        if isinstance(image, Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        label_mask = sample["mask"]
        if isinstance(label_mask, Tensor):
            label_mask = label_mask.numpy()

        showing_predictions = "prediction" in sample
        if showing_predictions:
            prediction_mask = sample["prediction"]
            if isinstance(prediction_mask, Tensor):
                prediction_mask = prediction_mask.numpy()

        return self._plot_sample(
            image,
            label_mask,
            self.num_classes,
            prediction=prediction_mask if showing_predictions else None,
            suptitle=suptitle,
            class_names=self.class_names,
            show_axes=show_axes,
        )

    @staticmethod
    def _plot_sample(image, label, num_classes, prediction=None, suptitle=None, class_names=None, show_axes=False):
        num_images = 5 if prediction is not None else 4
        fig, ax = plt.subplots(1, num_images, figsize=(12, 10), layout="compressed")
        axes_visibility = "on" if show_axes else "off"

        # for legend
        ax[0].axis("off")

        norm = mpl.colors.Normalize(vmin=0, vmax=num_classes - 1)
        ax[1].axis(axes_visibility)
        ax[1].title.set_text("Image")
        ax[1].imshow(image)

        ax[2].axis(axes_visibility)
        ax[2].title.set_text("Ground Truth Mask")
        ax[2].imshow(label, cmap="jet", norm=norm)

        ax[3].axis(axes_visibility)
        ax[3].title.set_text("GT Mask on Image")
        ax[3].imshow(image)
        ax[3].imshow(label, cmap="jet", alpha=0.3, norm=norm)

        if prediction is not None:
            ax[4].axis(axes_visibility)
            ax[4].title.set_text("Predicted Mask")
            ax[4].imshow(prediction, cmap="jet", norm=norm)

        cmap = plt.get_cmap("jet")
        legend_data = []
        for i, _ in enumerate(range(num_classes)):
            class_name = class_names[i] if class_names else str(i)
            data = [i, cmap(norm(i)), class_name]
            legend_data.append(data)
        handles = [Rectangle((0, 0), 1, 1, color=tuple(v for v in c)) for k, c, n in legend_data]
        labels = [n for k, c, n in legend_data]
        ax[0].legend(handles, labels, loc="center")
        if suptitle is not None:
            plt.suptitle(suptitle)
        return fig

__init__(data_root, num_classes, label_data_root=None, image_grep='*', label_grep='*', split=None, ignore_split_file_extensions=True, allow_substring_split_file=True, rgb_indices=None, dataset_bands=None, output_bands=None, class_names=None, constant_scale=1, transform=None, no_data_replace=None, no_label_replace=None, expand_temporal_dimension=False, reduce_zero_label=False) #

Constructor

Parameters:

Name Type Description Default
data_root Path

Path to data root directory

required
num_classes int

Number of classes in the dataset

required
label_data_root Path

Path to data root directory with labels. If not specified, will use the same as for images.

None
image_grep str

Regular expression appended to data_root to find input images. Defaults to "*".

'*'
label_grep str

Regular expression appended to data_root to find ground truth masks. Defaults to "*".

'*'
split Path

Path to file containing files to be used for this split. The file should be a new-line separated prefixes contained in the desired files. Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])

None
ignore_split_file_extensions bool

Whether to disregard extensions when using the split file to determine which files to include in the dataset. E.g. necessary for Eurosat, since the split files specify ".jpg" but files are actually ".jpg". Defaults to True

True
allow_substring_split_file bool

Whether the split files contain substrings that must be present in file names to be included (as in mmsegmentation), or exact matches (e.g. eurosat). Defaults to True.

True
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
dataset_bands list[HLSBands | int] | None

Bands present in the dataset.

None
output_bands list[HLSBands | int] | None

Bands that should be output by the dataset.

None
class_names list[str]

Class names. Defaults to None.

None
constant_scale float

Factor to multiply image values by. Defaults to 1.

1
transform Compose | None

Albumentations transform to be applied. Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input images with this value. If none, does no replacement. Defaults to None.

None
no_label_replace int | None

Replace nan values in label with this value. If none, does no replacement. Defaults to None.

None
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
Source code in terratorch/datasets/generic_pixel_wise_dataset.py
def __init__(
    self,
    data_root: Path,
    num_classes: int,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    ignore_split_file_extensions: bool = True,
    allow_substring_split_file: bool = True,
    rgb_indices: list[str] | None = None,
    dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    class_names: list[str] | None = None,
    constant_scale: float = 1,
    transform: A.Compose | None = None,
    no_data_replace: float | None = None,
    no_label_replace: int | None = None,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
) -> None:
    """Constructor

    Args:
        data_root (Path): Path to data root directory
        num_classes (int): Number of classes in the dataset
        label_data_root (Path, optional): Path to data root directory with labels.
            If not specified, will use the same as for images.
        image_grep (str, optional): Regular expression appended to data_root to find input images.
            Defaults to "*".
        label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
            Defaults to "*".
        split (Path, optional): Path to file containing files to be used for this split.
            The file should be a new-line separated prefixes contained in the desired files.
            Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
        ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
            file to determine which files to include in the dataset.
            E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
            actually ".jpg". Defaults to True
        allow_substring_split_file (bool, optional): Whether the split files contain substrings
            that must be present in file names to be included (as in mmsegmentation), or exact
            matches (e.g. eurosat). Defaults to True.
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
        output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
        class_names (list[str], optional): Class names. Defaults to None.
        constant_scale (float): Factor to multiply image values by. Defaults to 1.
        transform (Albumentations.Compose | None): Albumentations transform to be applied.
            Should end with ToTensorV2(). If used through the generic_data_module,
            should not include normalization. Not supported for multi-temporal data.
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
        no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to None.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
    """
    super().__init__(
        data_root,
        label_data_root=label_data_root,
        image_grep=image_grep,
        label_grep=label_grep,
        split=split,
        ignore_split_file_extensions=ignore_split_file_extensions,
        allow_substring_split_file=allow_substring_split_file,
        rgb_indices=rgb_indices,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        no_label_replace=no_label_replace,
        expand_temporal_dimension=expand_temporal_dimension,
        reduce_zero_label=reduce_zero_label,
    )
    self.num_classes = num_classes
    self.class_names = class_names

plot(sample, suptitle=None, show_axes=False) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None
show_axes bool | None

whether to show axes or not

False

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_pixel_wise_dataset.py
def plot(self, sample: dict[str, Tensor], suptitle: str | None = None, show_axes: bool | None = False) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample: a sample returned by :meth:`__getitem__`
        suptitle: optional string to use as a suptitle
        show_axes: whether to show axes or not

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """
    image = sample["image"]
    if len(image.shape) == 5:
        return
    if isinstance(image, Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    label_mask = sample["mask"]
    if isinstance(label_mask, Tensor):
        label_mask = label_mask.numpy()

    showing_predictions = "prediction" in sample
    if showing_predictions:
        prediction_mask = sample["prediction"]
        if isinstance(prediction_mask, Tensor):
            prediction_mask = prediction_mask.numpy()

    return self._plot_sample(
        image,
        label_mask,
        self.num_classes,
        prediction=prediction_mask if showing_predictions else None,
        suptitle=suptitle,
        class_names=self.class_names,
        show_axes=show_axes,
    )

terratorch.datasets.generic_pixel_wise_dataset.GenericNonGeoPixelwiseRegressionDataset #

Bases: GenericPixelWiseDataset

GenericNonGeoPixelwiseRegressionDataset

Source code in terratorch/datasets/generic_pixel_wise_dataset.py
class GenericNonGeoPixelwiseRegressionDataset(GenericPixelWiseDataset):
    """GenericNonGeoPixelwiseRegressionDataset"""

    def __init__(
        self,
        data_root: Path,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        ignore_split_file_extensions: bool = True,
        allow_substring_split_file: bool = True,
        rgb_indices: list[int] | None = None,
        dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        constant_scale: float = 1,
        transform: A.Compose | None = None,
        no_data_replace: float | None = None,
        no_label_replace: int | None = None,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
    ) -> None:
        """Constructor

        Args:
            data_root (Path): Path to data root directory
            label_data_root (Path, optional): Path to data root directory with labels.
                If not specified, will use the same as for images.
            image_grep (str, optional): Regular expression appended to data_root to find input images.
                Defaults to "*".
            label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
                Defaults to "*".
            split (Path, optional): Path to file containing files to be used for this split.
                The file should be a new-line separated prefixes contained in the desired files.
                Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
            ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
                file to determine which files to include in the dataset.
                E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
                actually ".jpg". Defaults to True.
            allow_substring_split_file (bool, optional): Whether the split files contain substrings
                that must be present in file names to be included (as in mmsegmentation), or exact
                matches (e.g. eurosat). Defaults to True.
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
            output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
            constant_scale (float): Factor to multiply image values by. Defaults to 1.
            transform (Albumentations.Compose | None): Albumentations transform to be applied.
                Should end with ToTensorV2(). If used through the generic_data_module,
                should not include normalization. Not supported for multi-temporal data.
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
            no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to None.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
        """
        super().__init__(
            data_root,
            label_data_root=label_data_root,
            image_grep=image_grep,
            label_grep=label_grep,
            split=split,
            ignore_split_file_extensions=ignore_split_file_extensions,
            allow_substring_split_file=allow_substring_split_file,
            rgb_indices=rgb_indices,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            no_label_replace=no_label_replace,
            expand_temporal_dimension=expand_temporal_dimension,
            reduce_zero_label=reduce_zero_label,
        )

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)
        if "mask" in item:
            item["mask"] = item["mask"].float()
        return item

    def plot(self, sample: dict[str, Tensor], suptitle: str | None = None, show_axes: bool | None = False) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
            suptitle (str|None): optional string to use as a suptitle
            show_axes (bool|None): whether to show axes or not

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """
        image = sample["image"]
        if len(image.shape) == 5:
            return
        if isinstance(image, Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        label_mask = sample["mask"]
        if isinstance(label_mask, Tensor):
            label_mask = label_mask.numpy()

        showing_predictions = "prediction" in sample
        if showing_predictions:
            prediction_mask = sample["prediction"]
            if isinstance(prediction_mask, Tensor):
                prediction_mask = prediction_mask.numpy()

        return self._plot_sample(
            image,
            label_mask,
            prediction=prediction_mask if showing_predictions else None,
            suptitle=suptitle,
            show_axes=show_axes,
        )

    @staticmethod
    def _plot_sample(image, label, prediction=None, suptitle=None, show_axes=False):
        num_images = 4 if prediction is not None else 3
        fig, ax = plt.subplots(1, num_images, figsize=(12, 10), layout="compressed")
        axes_visibility = "on" if show_axes else "off"

        norm = mpl.colors.Normalize(vmin=label.min(), vmax=label.max())
        ax[0].axis(axes_visibility)
        ax[0].title.set_text("Image")
        ax[0].imshow(image)

        ax[1].axis(axes_visibility)
        ax[1].title.set_text("Ground Truth Mask")
        ax[1].imshow(label, cmap="Greens", norm=norm)

        ax[2].axis(axes_visibility)
        ax[2].title.set_text("GT Mask on Image")
        ax[2].imshow(image)
        ax[2].imshow(label, cmap="Greens", alpha=0.3, norm=norm)
        # ax[2].legend()

        if prediction is not None:
            ax[3].axis(axes_visibility)
            ax[3].title.set_text("Predicted Mask")
            ax[3].imshow(prediction, cmap="Greens", norm=norm)

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

__init__(data_root, label_data_root=None, image_grep='*', label_grep='*', split=None, ignore_split_file_extensions=True, allow_substring_split_file=True, rgb_indices=None, dataset_bands=None, output_bands=None, constant_scale=1, transform=None, no_data_replace=None, no_label_replace=None, expand_temporal_dimension=False, reduce_zero_label=False) #

Constructor

Parameters:

Name Type Description Default
data_root Path

Path to data root directory

required
label_data_root Path

Path to data root directory with labels. If not specified, will use the same as for images.

None
image_grep str

Regular expression appended to data_root to find input images. Defaults to "*".

'*'
label_grep str

Regular expression appended to data_root to find ground truth masks. Defaults to "*".

'*'
split Path

Path to file containing files to be used for this split. The file should be a new-line separated prefixes contained in the desired files. Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])

None
ignore_split_file_extensions bool

Whether to disregard extensions when using the split file to determine which files to include in the dataset. E.g. necessary for Eurosat, since the split files specify ".jpg" but files are actually ".jpg". Defaults to True.

True
allow_substring_split_file bool

Whether the split files contain substrings that must be present in file names to be included (as in mmsegmentation), or exact matches (e.g. eurosat). Defaults to True.

True
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
dataset_bands list[HLSBands | int] | None

Bands present in the dataset.

None
output_bands list[HLSBands | int] | None

Bands that should be output by the dataset.

None
constant_scale float

Factor to multiply image values by. Defaults to 1.

1
transform Compose | None

Albumentations transform to be applied. Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input images with this value. If none, does no replacement. Defaults to None.

None
no_label_replace int | None

Replace nan values in label with this value. If none, does no replacement. Defaults to None.

None
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
Source code in terratorch/datasets/generic_pixel_wise_dataset.py
def __init__(
    self,
    data_root: Path,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    ignore_split_file_extensions: bool = True,
    allow_substring_split_file: bool = True,
    rgb_indices: list[int] | None = None,
    dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    constant_scale: float = 1,
    transform: A.Compose | None = None,
    no_data_replace: float | None = None,
    no_label_replace: int | None = None,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
) -> None:
    """Constructor

    Args:
        data_root (Path): Path to data root directory
        label_data_root (Path, optional): Path to data root directory with labels.
            If not specified, will use the same as for images.
        image_grep (str, optional): Regular expression appended to data_root to find input images.
            Defaults to "*".
        label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
            Defaults to "*".
        split (Path, optional): Path to file containing files to be used for this split.
            The file should be a new-line separated prefixes contained in the desired files.
            Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
        ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
            file to determine which files to include in the dataset.
            E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
            actually ".jpg". Defaults to True.
        allow_substring_split_file (bool, optional): Whether the split files contain substrings
            that must be present in file names to be included (as in mmsegmentation), or exact
            matches (e.g. eurosat). Defaults to True.
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
        output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
        constant_scale (float): Factor to multiply image values by. Defaults to 1.
        transform (Albumentations.Compose | None): Albumentations transform to be applied.
            Should end with ToTensorV2(). If used through the generic_data_module,
            should not include normalization. Not supported for multi-temporal data.
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
        no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to None.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
    """
    super().__init__(
        data_root,
        label_data_root=label_data_root,
        image_grep=image_grep,
        label_grep=label_grep,
        split=split,
        ignore_split_file_extensions=ignore_split_file_extensions,
        allow_substring_split_file=allow_substring_split_file,
        rgb_indices=rgb_indices,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        no_label_replace=no_label_replace,
        expand_temporal_dimension=expand_temporal_dimension,
        reduce_zero_label=reduce_zero_label,
    )

plot(sample, suptitle=None, show_axes=False) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None
show_axes bool | None

whether to show axes or not

False

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_pixel_wise_dataset.py
def plot(self, sample: dict[str, Tensor], suptitle: str | None = None, show_axes: bool | None = False) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
        suptitle (str|None): optional string to use as a suptitle
        show_axes (bool|None): whether to show axes or not

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """
    image = sample["image"]
    if len(image.shape) == 5:
        return
    if isinstance(image, Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    label_mask = sample["mask"]
    if isinstance(label_mask, Tensor):
        label_mask = label_mask.numpy()

    showing_predictions = "prediction" in sample
    if showing_predictions:
        prediction_mask = sample["prediction"]
        if isinstance(prediction_mask, Tensor):
            prediction_mask = prediction_mask.numpy()

    return self._plot_sample(
        image,
        label_mask,
        prediction=prediction_mask if showing_predictions else None,
        suptitle=suptitle,
        show_axes=show_axes,
    )

terratorch.datasets.generic_pixel_wise_dataset.GenericPixelWiseDataset #

Bases: NonGeoDataset, ABC

This is a generic dataset class to be used for instantiating datasets from arguments. Ideally, one would create a dataset class specific to a dataset.

Source code in terratorch/datasets/generic_pixel_wise_dataset.py
class GenericPixelWiseDataset(NonGeoDataset, ABC):
    """
    This is a generic dataset class to be used for instantiating datasets from arguments.
    Ideally, one would create a dataset class specific to a dataset.
    """

    def __init__(
        self,
        data_root: Path,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        ignore_split_file_extensions: bool = True,
        allow_substring_split_file: bool = True,
        rgb_indices: list[int] | None = None,
        dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        constant_scale: float = 1,
        transform: A.Compose | None = None,
        no_data_replace: float | None = None,
        no_label_replace: int | None = None,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
    ) -> None:
        """Constructor

        Args:
            data_root (Path): Path to data root directory
            label_data_root (Path, optional): Path to data root directory with labels.
                If not specified, will use the same as for images.
            image_grep (str, optional): Regular expression appended to data_root to find input images.
                Defaults to "*".
            label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
                Defaults to "*".
            split (Path, optional): Path to file containing files to be used for this split.
                The file should be a new-line separated prefixes contained in the desired files.
                Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
            ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
                file to determine which files to include in the dataset.
                E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
                actually ".jpg". Defaults to True.
            allow_substring_split_file (bool, optional): Whether the split files contain substrings
                that must be present in file names to be included (as in mmsegmentation), or exact
                matches (e.g. eurosat). Defaults to True.
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            dataset_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands present in the dataset. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be refered to by output_bands. Defaults to None.
            output_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands that should be output by the dataset as named by dataset_bands.
            constant_scale (float): Factor to multiply image values by. Defaults to 1.
            transform (Albumentations.Compose | None): Albumentations transform to be applied.
                Should end with ToTensorV2(). If used through the generic_data_module,
                should not include normalization. Not supported for multi-temporal data.
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
            no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to -1.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
        """
        super().__init__()

        self.split_file = split

        label_data_root = label_data_root if label_data_root is not None else data_root
        self.image_files = sorted(glob.glob(os.path.join(data_root, image_grep)))
        self.constant_scale = constant_scale
        self.no_data_replace = no_data_replace
        self.no_label_replace = no_label_replace
        self.segmentation_mask_files = sorted(glob.glob(os.path.join(label_data_root, label_grep)))
        self.reduce_zero_label = reduce_zero_label
        self.expand_temporal_dimension = expand_temporal_dimension

        if self.expand_temporal_dimension and output_bands is None:
            msg = "Please provide output_bands when expand_temporal_dimension is True"
            raise Exception(msg)
        if self.split_file is not None:
            with open(self.split_file) as f:
                split = f.readlines()
            valid_files = {rf"{substring.strip()}" for substring in split}
            self.image_files = filter_valid_files(
                self.image_files,
                valid_files=valid_files,
                ignore_extensions=ignore_split_file_extensions,
                allow_substring=allow_substring_split_file,
            )
            self.segmentation_mask_files = filter_valid_files(
                self.segmentation_mask_files,
                valid_files=valid_files,
                ignore_extensions=ignore_split_file_extensions,
                allow_substring=allow_substring_split_file,
            )

        # We don't define a split file for prediction
        if not self.split_file:
            # When prediction is enabled, we don't have mask files, so
            # we need to provide a way to run the dataloder in these cases.
            if not self.segmentation_mask_files:
                self.segmentation_mask_files = self.image_files
                # The masks can be `None` since they won't be used in fact. 

        self.rgb_indices = [0, 1, 2] if rgb_indices is None else rgb_indices

        self.dataset_bands = generate_bands_intervals(dataset_bands)
        self.output_bands = generate_bands_intervals(output_bands)

        if self.output_bands and not self.dataset_bands:
            msg = "If output bands provided, dataset_bands must also be provided"
            return Exception(msg)  # noqa: PLE0101

        # There is a special condition if the bands are defined as simple strings.
        if self.output_bands:
            if len(set(self.output_bands) & set(self.dataset_bands)) != len(self.output_bands):
                msg = "Output bands must be a subset of dataset bands"
                raise Exception(msg)

            self.filter_indices = [self.dataset_bands.index(band) for band in self.output_bands]

        else:
            self.filter_indices = None

        # If no transform is given, apply only to transform to torch tensor
        self.transform = transform if transform else default_transform
        # self.transform = transform if transform else ToTensorV2()

        import warnings

        import rasterio

        warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)

    def __len__(self) -> int:
        return len(self.image_files)

    def __getitem__(self, index: int) -> dict[str, Any]:
        image = self._load_file(self.image_files[index], nan_replace=self.no_data_replace).to_numpy()
        # to channels last
        if self.expand_temporal_dimension:
            image = rearrange(image, "(channels time) h w -> channels time h w", channels=len(self.output_bands))
        image = np.moveaxis(image, 0, -1)

        if self.filter_indices:
            image = image[..., self.filter_indices]
        output = {
            "image": image.astype(np.float32) * self.constant_scale,
        }
        if self.segmentation_mask_files:
            mask = self._load_file(self.segmentation_mask_files[index], nan_replace=self.no_label_replace)
            output["mask"] = mask.to_numpy()[0]
            if self.reduce_zero_label:
                output["mask"] -= 1
        if self.transform:
            output = self.transform(**output)
        output["filename"] = self.image_files[index]

        return output

    def _load_file(self, path, nan_replace: int | float | None = None) -> xr.DataArray:
        data = rioxarray.open_rasterio(path, masked=True)
        if nan_replace is not None:
            data = data.fillna(nan_replace)
        return data

__init__(data_root, label_data_root=None, image_grep='*', label_grep='*', split=None, ignore_split_file_extensions=True, allow_substring_split_file=True, rgb_indices=None, dataset_bands=None, output_bands=None, constant_scale=1, transform=None, no_data_replace=None, no_label_replace=None, expand_temporal_dimension=False, reduce_zero_label=False) #

Constructor

Parameters:

Name Type Description Default
data_root Path

Path to data root directory

required
label_data_root Path

Path to data root directory with labels. If not specified, will use the same as for images.

None
image_grep str

Regular expression appended to data_root to find input images. Defaults to "*".

'*'
label_grep str

Regular expression appended to data_root to find ground truth masks. Defaults to "*".

'*'
split Path

Path to file containing files to be used for this split. The file should be a new-line separated prefixes contained in the desired files. Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])

None
ignore_split_file_extensions bool

Whether to disregard extensions when using the split file to determine which files to include in the dataset. E.g. necessary for Eurosat, since the split files specify ".jpg" but files are actually ".jpg". Defaults to True.

True
allow_substring_split_file bool

Whether the split files contain substrings that must be present in file names to be included (as in mmsegmentation), or exact matches (e.g. eurosat). Defaults to True.

True
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
dataset_bands list[HLSBands | int | tuple[int, int] | str] | None

Bands present in the dataset. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be refered to by output_bands. Defaults to None.

None
output_bands list[HLSBands | int | tuple[int, int] | str] | None

Bands that should be output by the dataset as named by dataset_bands.

None
constant_scale float

Factor to multiply image values by. Defaults to 1.

1
transform Compose | None

Albumentations transform to be applied. Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input images with this value. If none, does no replacement. Defaults to None.

None
no_label_replace int | None

Replace nan values in label with this value. If none, does no replacement. Defaults to -1.

None
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
Source code in terratorch/datasets/generic_pixel_wise_dataset.py
def __init__(
    self,
    data_root: Path,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    ignore_split_file_extensions: bool = True,
    allow_substring_split_file: bool = True,
    rgb_indices: list[int] | None = None,
    dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    constant_scale: float = 1,
    transform: A.Compose | None = None,
    no_data_replace: float | None = None,
    no_label_replace: int | None = None,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
) -> None:
    """Constructor

    Args:
        data_root (Path): Path to data root directory
        label_data_root (Path, optional): Path to data root directory with labels.
            If not specified, will use the same as for images.
        image_grep (str, optional): Regular expression appended to data_root to find input images.
            Defaults to "*".
        label_grep (str, optional): Regular expression appended to data_root to find ground truth masks.
            Defaults to "*".
        split (Path, optional): Path to file containing files to be used for this split.
            The file should be a new-line separated prefixes contained in the desired files.
            Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
        ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
            file to determine which files to include in the dataset.
            E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
            actually ".jpg". Defaults to True.
        allow_substring_split_file (bool, optional): Whether the split files contain substrings
            that must be present in file names to be included (as in mmsegmentation), or exact
            matches (e.g. eurosat). Defaults to True.
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        dataset_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands present in the dataset. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be refered to by output_bands. Defaults to None.
        output_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands that should be output by the dataset as named by dataset_bands.
        constant_scale (float): Factor to multiply image values by. Defaults to 1.
        transform (Albumentations.Compose | None): Albumentations transform to be applied.
            Should end with ToTensorV2(). If used through the generic_data_module,
            should not include normalization. Not supported for multi-temporal data.
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input images with this value. If none, does no replacement. Defaults to None.
        no_label_replace (int | None): Replace nan values in label with this value. If none, does no replacement. Defaults to -1.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
    """
    super().__init__()

    self.split_file = split

    label_data_root = label_data_root if label_data_root is not None else data_root
    self.image_files = sorted(glob.glob(os.path.join(data_root, image_grep)))
    self.constant_scale = constant_scale
    self.no_data_replace = no_data_replace
    self.no_label_replace = no_label_replace
    self.segmentation_mask_files = sorted(glob.glob(os.path.join(label_data_root, label_grep)))
    self.reduce_zero_label = reduce_zero_label
    self.expand_temporal_dimension = expand_temporal_dimension

    if self.expand_temporal_dimension and output_bands is None:
        msg = "Please provide output_bands when expand_temporal_dimension is True"
        raise Exception(msg)
    if self.split_file is not None:
        with open(self.split_file) as f:
            split = f.readlines()
        valid_files = {rf"{substring.strip()}" for substring in split}
        self.image_files = filter_valid_files(
            self.image_files,
            valid_files=valid_files,
            ignore_extensions=ignore_split_file_extensions,
            allow_substring=allow_substring_split_file,
        )
        self.segmentation_mask_files = filter_valid_files(
            self.segmentation_mask_files,
            valid_files=valid_files,
            ignore_extensions=ignore_split_file_extensions,
            allow_substring=allow_substring_split_file,
        )

    # We don't define a split file for prediction
    if not self.split_file:
        # When prediction is enabled, we don't have mask files, so
        # we need to provide a way to run the dataloder in these cases.
        if not self.segmentation_mask_files:
            self.segmentation_mask_files = self.image_files
            # The masks can be `None` since they won't be used in fact. 

    self.rgb_indices = [0, 1, 2] if rgb_indices is None else rgb_indices

    self.dataset_bands = generate_bands_intervals(dataset_bands)
    self.output_bands = generate_bands_intervals(output_bands)

    if self.output_bands and not self.dataset_bands:
        msg = "If output bands provided, dataset_bands must also be provided"
        return Exception(msg)  # noqa: PLE0101

    # There is a special condition if the bands are defined as simple strings.
    if self.output_bands:
        if len(set(self.output_bands) & set(self.dataset_bands)) != len(self.output_bands):
            msg = "Output bands must be a subset of dataset bands"
            raise Exception(msg)

        self.filter_indices = [self.dataset_bands.index(band) for band in self.output_bands]

    else:
        self.filter_indices = None

    # If no transform is given, apply only to transform to torch tensor
    self.transform = transform if transform else default_transform
    # self.transform = transform if transform else ToTensorV2()

    import warnings

    import rasterio

    warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)

terratorch.datasets.generic_scalar_label_dataset.GenericNonGeoClassificationDataset #

Bases: GenericScalarLabelDataset

GenericNonGeoClassificationDataset

Source code in terratorch/datasets/generic_scalar_label_dataset.py
class GenericNonGeoClassificationDataset(GenericScalarLabelDataset):
    """GenericNonGeoClassificationDataset"""

    def __init__(
        self,
        data_root: Path,
        num_classes: int,
        split: Path | None = None,
        require_label: bool = True,
        ignore_split_file_extensions: bool = True,  # noqa: FBT001, FBT002
        allow_substring_split_file: bool = True,  # noqa: FBT001, FBT002
        rgb_indices: list[str] | None = None,
        dataset_bands: list[HLSBands | int] | None = None,
        output_bands: list[HLSBands | int] | None = None,
        class_names: list[str] | None = None,
        constant_scale: float = 1,
        transform: A.Compose | None = None,
        no_data_replace: float = 0,
        expand_temporal_dimension: bool = False,  # noqa: FBT001, FBT002
    ) -> None:
        """A generic Non-Geo dataset for classification.

        Args:
            data_root (Path): Path to data root directory
            num_classes (int): Number of classes in the dataset
            split (Path, optional): Path to file containing files to be used for this split.
                The file should be a new-line separated prefixes contained in the desired files.
                Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
            ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
                file to determine which files to include in the dataset.
                E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
                actually ".jpg". Defaults to True.
            allow_substring_split_file (bool, optional): Whether the split files contain substrings
                that must be present in file names to be included (as in mmsegmentation), or exact
                matches (e.g. eurosat). Defaults to True.
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
            output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
            class_names (list[str], optional): Class names. Defaults to None.
            constant_scale (float): Factor to multiply image values by. Defaults to 1.
            transform (Albumentations.Compose | None): Albumentations transform to be applied.
                Should end with ToTensorV2(). If used through the generic_data_module,
                should not include normalization. Not supported for multi-temporal data.
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float): Replace nan values in input images with this value. Defaults to 0.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Defaults to False.
        """
        super().__init__(
            data_root,
            split=split,
            require_label=require_label,
            ignore_split_file_extensions=ignore_split_file_extensions,
            allow_substring_split_file=allow_substring_split_file,
            rgb_indices=rgb_indices,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            expand_temporal_dimension=expand_temporal_dimension,
        )
        self.num_classes = num_classes
        self.class_names = class_names

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)
        if "label" in item:
            item["label"] = torch.tensor(item["label"]).long()
        return item

    def plot(self, sample: dict[str, Tensor], suptitle: str | None = None) -> Figure:
        pass

__init__(data_root, num_classes, split=None, require_label=True, ignore_split_file_extensions=True, allow_substring_split_file=True, rgb_indices=None, dataset_bands=None, output_bands=None, class_names=None, constant_scale=1, transform=None, no_data_replace=0, expand_temporal_dimension=False) #

A generic Non-Geo dataset for classification.

Parameters:

Name Type Description Default
data_root Path

Path to data root directory

required
num_classes int

Number of classes in the dataset

required
split Path

Path to file containing files to be used for this split. The file should be a new-line separated prefixes contained in the desired files. Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])

None
ignore_split_file_extensions bool

Whether to disregard extensions when using the split file to determine which files to include in the dataset. E.g. necessary for Eurosat, since the split files specify ".jpg" but files are actually ".jpg". Defaults to True.

True
allow_substring_split_file bool

Whether the split files contain substrings that must be present in file names to be included (as in mmsegmentation), or exact matches (e.g. eurosat). Defaults to True.

True
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
dataset_bands list[HLSBands | int] | None

Bands present in the dataset.

None
output_bands list[HLSBands | int] | None

Bands that should be output by the dataset.

None
class_names list[str]

Class names. Defaults to None.

None
constant_scale float

Factor to multiply image values by. Defaults to 1.

1
transform Compose | None

Albumentations transform to be applied. Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float

Replace nan values in input images with this value. Defaults to 0.

0
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Defaults to False.

False
Source code in terratorch/datasets/generic_scalar_label_dataset.py
def __init__(
    self,
    data_root: Path,
    num_classes: int,
    split: Path | None = None,
    require_label: bool = True,
    ignore_split_file_extensions: bool = True,  # noqa: FBT001, FBT002
    allow_substring_split_file: bool = True,  # noqa: FBT001, FBT002
    rgb_indices: list[str] | None = None,
    dataset_bands: list[HLSBands | int] | None = None,
    output_bands: list[HLSBands | int] | None = None,
    class_names: list[str] | None = None,
    constant_scale: float = 1,
    transform: A.Compose | None = None,
    no_data_replace: float = 0,
    expand_temporal_dimension: bool = False,  # noqa: FBT001, FBT002
) -> None:
    """A generic Non-Geo dataset for classification.

    Args:
        data_root (Path): Path to data root directory
        num_classes (int): Number of classes in the dataset
        split (Path, optional): Path to file containing files to be used for this split.
            The file should be a new-line separated prefixes contained in the desired files.
            Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
        ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
            file to determine which files to include in the dataset.
            E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
            actually ".jpg". Defaults to True.
        allow_substring_split_file (bool, optional): Whether the split files contain substrings
            that must be present in file names to be included (as in mmsegmentation), or exact
            matches (e.g. eurosat). Defaults to True.
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        dataset_bands (list[HLSBands | int] | None): Bands present in the dataset.
        output_bands (list[HLSBands | int] | None): Bands that should be output by the dataset.
        class_names (list[str], optional): Class names. Defaults to None.
        constant_scale (float): Factor to multiply image values by. Defaults to 1.
        transform (Albumentations.Compose | None): Albumentations transform to be applied.
            Should end with ToTensorV2(). If used through the generic_data_module,
            should not include normalization. Not supported for multi-temporal data.
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float): Replace nan values in input images with this value. Defaults to 0.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Defaults to False.
    """
    super().__init__(
        data_root,
        split=split,
        require_label=require_label,
        ignore_split_file_extensions=ignore_split_file_extensions,
        allow_substring_split_file=allow_substring_split_file,
        rgb_indices=rgb_indices,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        expand_temporal_dimension=expand_temporal_dimension,
    )
    self.num_classes = num_classes
    self.class_names = class_names

terratorch.datasets.generic_scalar_label_dataset.GenericScalarLabelDataset #

Bases: NonGeoDataset, ImageFolder, ABC

This is a generic dataset class to be used for instantiating datasets from arguments. Ideally, one would create a dataset class specific to a dataset.

Source code in terratorch/datasets/generic_scalar_label_dataset.py
class GenericScalarLabelDataset(NonGeoDataset, ImageFolder, ABC):
    """
    This is a generic dataset class to be used for instantiating datasets from arguments.
    Ideally, one would create a dataset class specific to a dataset.
    """

    def __init__(
        self,
        data_root: Path,
        split: Path | None = None,
        require_label: bool = True,
        ignore_split_file_extensions: bool = True,  # noqa: FBT001, FBT002
        allow_substring_split_file: bool = True,  # noqa: FBT001, FBT002
        rgb_indices: list[int] | None = None,
        dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        constant_scale: float = 1,
        transform: A.Compose | None = None,
        no_data_replace: float = 0,
        expand_temporal_dimension: bool = False,  # noqa: FBT001, FBT002
    ) -> None:
        """Constructor

        Args:
            data_root (Path): Path to data root directory
            split (Path, optional): Path to file containing files to be used for this split.
                The file should be a new-line separated prefixes contained in the desired files.
                Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
            ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
                file to determine which files to include in the dataset.
                E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
                actually ".jpg". Defaults to True.
            allow_substring_split_file (bool, optional): Whether the split files contain substrings
                that must be present in file names to be included (as in mmsegmentation), or exact
                matches (e.g. eurosat). Defaults to True.
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            dataset_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands present in the dataset. This
                parameter gives identifiers to input channels (bands) so that they can then be refered to by
                output_bands. Can use the HLSBands enum, ints, int ranges, or strings. Defaults to None.
            output_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands that should be output by the
                dataset as named by dataset_bands.
            constant_scale (float): Factor to multiply image values by. Defaults to 1.
            transform (Albumentations.Compose | None): Albumentations transform to be applied.
                Should end with ToTensorV2(). If used through the generic_data_module,
                should not include normalization. Not supported for multi-temporal data.
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float): Replace nan values in input images with this value. Defaults to 0.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Defaults to False.
        """
        self.split_file = split
        self.split = split
        self.require_label = require_label
        self.image_files = sorted(glob.glob(os.path.join(data_root, "**"), recursive=True))
        self.image_files = [f for f in self.image_files if not os.path.isdir(f)]
        self.constant_scale = constant_scale
        self.no_data_replace = no_data_replace
        self.expand_temporal_dimension = expand_temporal_dimension
        if self.expand_temporal_dimension and output_bands is None:
            msg = "Please provide output_bands when expand_temporal_dimension is True"
            raise Exception(msg)
        if self.split_file is not None:
            with open(self.split_file) as f:
                split = f.readlines()
            valid_files = {rf"{substring.strip()}" for substring in split}
            self.image_files = filter_valid_files(
                self.image_files,
                valid_files=valid_files,
                ignore_extensions=ignore_split_file_extensions,
                allow_substring=allow_substring_split_file,
            )

            def is_valid_file(x):
                return x in self.image_files

        else:

            def is_valid_file(x):
                return True

        # Checking if it's necessary to overwrite the `find_classes` method
        try:
            _, _ = self.find_classes(data_root)
        except FileNotFoundError:
            self.find_classes = self.find_classes_

        super().__init__(
            root=data_root, transform=None, target_transform=None, loader=rasterio_loader, is_valid_file=is_valid_file
        )

        self.rgb_indices = [0, 1, 2] if rgb_indices is None else rgb_indices

        self.dataset_bands = generate_bands_intervals(dataset_bands)
        self.output_bands = generate_bands_intervals(output_bands)

        if self.output_bands and not self.dataset_bands:
            msg = "If output bands provided, dataset_bands must also be provided"
            return Exception(msg)  # noqa: PLE0101

        # There is a special condition if the bands are defined as simple strings.
        if self.output_bands:
            if len(set(self.output_bands) & set(self.dataset_bands)) != len(self.output_bands):
                msg = "Output bands must be a subset of dataset bands"
                raise Exception(msg)

            self.filter_indices = [self.dataset_bands.index(band) for band in self.output_bands]

        else:
            self.filter_indices = None
        # If no transform is given, apply only to transform to torch tensor
        self.transforms = transform if transform else default_transform
        # self.transform = transform if transform else ToTensorV2()

        import warnings

        import rasterio

        warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)

    def __len__(self) -> int:
        return len(self.image_files)

    def _loader(self, path: str | Path) -> Image.Image:
        try:
            with open(path, "rb") as f:
                img = np.asarray(Image.open(f))
        except PIL.UnidentifiedImageError:
            # TIFF files containing floating-point values should be handled in
            # another way.
            if path.endswith(".tif") or path.endswith(".tiff"):
                img = tifffile.imread(path)
            else:
                raise OSError(f"Could not open {path}. Unsupported format or configuration.")
        return img

    def __base_getitem__(self, index: int) -> tuple[Any, Any]:
        """
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        """
        path, target = self.samples[index]
        sample = self._loader(path)

        return sample, target

    def __getitem__(self, index: int) -> dict[str, Any]:
        image, label = self.__base_getitem__(index)

        if self.expand_temporal_dimension:
            image = rearrange(image, "h w (channels time) -> time h w channels", channels=len(self.output_bands))
        if self.filter_indices:
            image = image[..., self.filter_indices]

        image = image.astype(np.float32) * self.constant_scale

        if self.transforms:
            image = self.transforms(image=image)["image"]  # albumentations returns dict

        if self.require_label:
            output = {
                "image": image,
                "label": label,  # samples is an attribute of ImageFolder. Contains a tuple of (Path, Target)
                "filename": self.image_files[index],
            }
        else:
            output = {
                "image": image,
                "filename": self.image_files[index],
            }

        return output

    def _generate_bands_intervals(self, bands_intervals: list[int | str | HLSBands | tuple[int]] | None = None):
        if bands_intervals is None:
            return None
        bands = []
        for element in bands_intervals:
            # if its an interval
            if isinstance(element, tuple):
                if len(element) != 2:  # noqa: PLR2004
                    msg = "When defining an interval, a tuple of two integers should be passed,\
                    defining start and end indices inclusive"
                    raise Exception(msg)
                expanded_element = list(range(element[0], element[1] + 1))
                bands.extend(expanded_element)
            else:
                bands.append(element)
        return bands

    def _load_file(self, path) -> xr.DataArray:
        data = rioxarray.open_rasterio(path, masked=True)
        data = data.fillna(self.no_data_replace)
        return data

    def find_classes_(self, directory: str | Path) -> tuple[list[str], dict[str, int]]:
        return ["./"], {"./": 0}

__base_getitem__(index) #

Parameters:

Name Type Description Default
index int

Index

required

Returns:

Name Type Description
tuple tuple[Any, Any]

(sample, target) where target is class_index of the target class.

Source code in terratorch/datasets/generic_scalar_label_dataset.py
def __base_getitem__(self, index: int) -> tuple[Any, Any]:
    """
    Args:
        index (int): Index

    Returns:
        tuple: (sample, target) where target is class_index of the target class.
    """
    path, target = self.samples[index]
    sample = self._loader(path)

    return sample, target

__init__(data_root, split=None, require_label=True, ignore_split_file_extensions=True, allow_substring_split_file=True, rgb_indices=None, dataset_bands=None, output_bands=None, constant_scale=1, transform=None, no_data_replace=0, expand_temporal_dimension=False) #

Constructor

Parameters:

Name Type Description Default
data_root Path

Path to data root directory

required
split Path

Path to file containing files to be used for this split. The file should be a new-line separated prefixes contained in the desired files. Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])

None
ignore_split_file_extensions bool

Whether to disregard extensions when using the split file to determine which files to include in the dataset. E.g. necessary for Eurosat, since the split files specify ".jpg" but files are actually ".jpg". Defaults to True.

True
allow_substring_split_file bool

Whether the split files contain substrings that must be present in file names to be included (as in mmsegmentation), or exact matches (e.g. eurosat). Defaults to True.

True
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
dataset_bands list[HLSBands | int | tuple[int, int] | str] | None

Bands present in the dataset. This parameter gives identifiers to input channels (bands) so that they can then be refered to by output_bands. Can use the HLSBands enum, ints, int ranges, or strings. Defaults to None.

None
output_bands list[HLSBands | int | tuple[int, int] | str] | None

Bands that should be output by the dataset as named by dataset_bands.

None
constant_scale float

Factor to multiply image values by. Defaults to 1.

1
transform Compose | None

Albumentations transform to be applied. Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float

Replace nan values in input images with this value. Defaults to 0.

0
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Defaults to False.

False
Source code in terratorch/datasets/generic_scalar_label_dataset.py
def __init__(
    self,
    data_root: Path,
    split: Path | None = None,
    require_label: bool = True,
    ignore_split_file_extensions: bool = True,  # noqa: FBT001, FBT002
    allow_substring_split_file: bool = True,  # noqa: FBT001, FBT002
    rgb_indices: list[int] | None = None,
    dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    constant_scale: float = 1,
    transform: A.Compose | None = None,
    no_data_replace: float = 0,
    expand_temporal_dimension: bool = False,  # noqa: FBT001, FBT002
) -> None:
    """Constructor

    Args:
        data_root (Path): Path to data root directory
        split (Path, optional): Path to file containing files to be used for this split.
            The file should be a new-line separated prefixes contained in the desired files.
            Files will be seached using glob with the form Path(data_root).glob(prefix + [image or label grep])
        ignore_split_file_extensions (bool, optional): Whether to disregard extensions when using the split
            file to determine which files to include in the dataset.
            E.g. necessary for Eurosat, since the split files specify ".jpg" but files are
            actually ".jpg". Defaults to True.
        allow_substring_split_file (bool, optional): Whether the split files contain substrings
            that must be present in file names to be included (as in mmsegmentation), or exact
            matches (e.g. eurosat). Defaults to True.
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        dataset_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands present in the dataset. This
            parameter gives identifiers to input channels (bands) so that they can then be refered to by
            output_bands. Can use the HLSBands enum, ints, int ranges, or strings. Defaults to None.
        output_bands (list[HLSBands | int | tuple[int, int] | str] | None): Bands that should be output by the
            dataset as named by dataset_bands.
        constant_scale (float): Factor to multiply image values by. Defaults to 1.
        transform (Albumentations.Compose | None): Albumentations transform to be applied.
            Should end with ToTensorV2(). If used through the generic_data_module,
            should not include normalization. Not supported for multi-temporal data.
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float): Replace nan values in input images with this value. Defaults to 0.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Defaults to False.
    """
    self.split_file = split
    self.split = split
    self.require_label = require_label
    self.image_files = sorted(glob.glob(os.path.join(data_root, "**"), recursive=True))
    self.image_files = [f for f in self.image_files if not os.path.isdir(f)]
    self.constant_scale = constant_scale
    self.no_data_replace = no_data_replace
    self.expand_temporal_dimension = expand_temporal_dimension
    if self.expand_temporal_dimension and output_bands is None:
        msg = "Please provide output_bands when expand_temporal_dimension is True"
        raise Exception(msg)
    if self.split_file is not None:
        with open(self.split_file) as f:
            split = f.readlines()
        valid_files = {rf"{substring.strip()}" for substring in split}
        self.image_files = filter_valid_files(
            self.image_files,
            valid_files=valid_files,
            ignore_extensions=ignore_split_file_extensions,
            allow_substring=allow_substring_split_file,
        )

        def is_valid_file(x):
            return x in self.image_files

    else:

        def is_valid_file(x):
            return True

    # Checking if it's necessary to overwrite the `find_classes` method
    try:
        _, _ = self.find_classes(data_root)
    except FileNotFoundError:
        self.find_classes = self.find_classes_

    super().__init__(
        root=data_root, transform=None, target_transform=None, loader=rasterio_loader, is_valid_file=is_valid_file
    )

    self.rgb_indices = [0, 1, 2] if rgb_indices is None else rgb_indices

    self.dataset_bands = generate_bands_intervals(dataset_bands)
    self.output_bands = generate_bands_intervals(output_bands)

    if self.output_bands and not self.dataset_bands:
        msg = "If output bands provided, dataset_bands must also be provided"
        return Exception(msg)  # noqa: PLE0101

    # There is a special condition if the bands are defined as simple strings.
    if self.output_bands:
        if len(set(self.output_bands) & set(self.dataset_bands)) != len(self.output_bands):
            msg = "Output bands must be a subset of dataset bands"
            raise Exception(msg)

        self.filter_indices = [self.dataset_bands.index(band) for band in self.output_bands]

    else:
        self.filter_indices = None
    # If no transform is given, apply only to transform to torch tensor
    self.transforms = transform if transform else default_transform
    # self.transform = transform if transform else ToTensorV2()

    import warnings

    import rasterio

    warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)

terratorch.datasets.generic_multimodal_dataset.GenericMultimodalSegmentationDataset #

Bases: GenericMultimodalDataset

GenericNonGeoSegmentationDataset

Source code in terratorch/datasets/generic_multimodal_dataset.py
class GenericMultimodalSegmentationDataset(GenericMultimodalDataset):
    """GenericNonGeoSegmentationDataset"""

    def __init__(
        self,
        data_root: Path,
        num_classes: int,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        image_modalities: list[str] | None = None,
        rgb_modality: str | None = None,
        rgb_indices: list[str] | None = None,
        allow_missing_modalities: bool = False,
        allow_substring_file_names: bool = False,
        dataset_bands: dict[list] | None = None,
        output_bands: dict[list] | None = None,
        class_names: list[str] | None = None,
        constant_scale: dict[float] = 1.0,
        transform: A.Compose | None = None,
        no_data_replace: float | None = None,
        no_label_replace: int | None = -1,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
        channel_position: int = -3,
        concat_bands: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """Constructor

        Args:
            data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
                data, with modalities as keys.
            num_classes (int): Number of classes.
            label_data_root (Path): Path to data root directory with mask files. Set to None for prediction mode.
            image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
                images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
            label_grep (str, optional): Regular expression appended to label_data_root to find mask files.
                Defaults to "*". Ignored when allow_substring_file_names is False.
            split (Path, optional): Path to file containing samples prefixes to be used for this split.
                The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
                sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
                files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
                If not specified, search samples based on files in data_root. Defaults to None.
            image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
                The difference between all modalities and image_modalities are non-image modalities which are treated
                differently during the transforms and are not modified but only converted into a tensor if possible.
            rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
            allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
                image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
                If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
                Defaults to True.
            dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
                as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
                that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
                of all modalities. Defaults to None.
            output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
                provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
            class_names (list[str], optional): Names of the classes. Defaults to None.
            constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
                keys. Can be subset of all modalities. Defaults to None.
            transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
                modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
                Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
                Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
                converted to tensors if possible. If dict, can include multiple transforms per modality which are
                applied separately (no shared parameters between modalities).
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input data with this value.
                If None, does no replacement. Defaults to None.
            no_label_replace (float | None): Replace nan values in label with this value.
                If none, does no replacement. Defaults to -1.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Only works with image modalities. Is only applied to modalities with defined dataset_bands.
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
            channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
            concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
                that it can be processed by single-modal models. Concatenate in the order of provided modalities.
                Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
        """

        super().__init__(
            data_root,
            label_data_root=label_data_root,
            image_grep=image_grep,
            label_grep=label_grep,
            split=split,
            image_modalities=image_modalities,
            rgb_modality=rgb_modality,
            rgb_indices=rgb_indices,
            allow_missing_modalities=allow_missing_modalities,
            allow_substring_file_names=allow_substring_file_names,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            no_label_replace=no_label_replace,
            expand_temporal_dimension=expand_temporal_dimension,
            reduce_zero_label=reduce_zero_label,
            channel_position=channel_position,
            concat_bands=concat_bands,
            *args,
            **kwargs,
        )
        self.num_classes = num_classes
        self.class_names = class_names

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)

        if "mask" in item:
            item["mask"] = item["mask"].long()

        return item

    def plot(
        self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
    ) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample: a sample returned by :meth:`__getitem__`
            suptitle: optional string to use as a suptitle
            show_axes: whether to show axes or not

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """
        image = sample["image"]
        if isinstance(image, dict):
            image = image[self.rgb_modality]
        if isinstance(image, torch.Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        label_mask = sample["mask"]
        if isinstance(label_mask, torch.Tensor):
            label_mask = label_mask.numpy()

        showing_predictions = "prediction" in sample
        if showing_predictions:
            prediction_mask = sample["prediction"]
            if isinstance(prediction_mask, torch.Tensor):
                prediction_mask = prediction_mask.numpy()

        return self._plot_sample(
            image,
            label_mask,
            self.num_classes,
            prediction=prediction_mask if showing_predictions else None,
            suptitle=suptitle,
            class_names=self.class_names,
            show_axes=show_axes,
        )

    @staticmethod
    def _plot_sample(image, label, num_classes, prediction=None, suptitle=None, class_names=None, show_axes=False):
        num_images = 5 if prediction is not None else 4
        fig, ax = plt.subplots(1, num_images, figsize=(12, 10), layout="compressed")
        axes_visibility = "on" if show_axes else "off"

        # for legend
        ax[0].axis("off")

        norm = mpl.colors.Normalize(vmin=0, vmax=num_classes - 1)
        ax[1].axis(axes_visibility)
        ax[1].title.set_text("Image")
        ax[1].imshow(image)

        ax[2].axis(axes_visibility)
        ax[2].title.set_text("Ground Truth Mask")
        ax[2].imshow(label, cmap="jet", norm=norm)

        ax[3].axis(axes_visibility)
        ax[3].title.set_text("GT Mask on Image")
        ax[3].imshow(image)
        ax[3].imshow(label, cmap="jet", alpha=0.3, norm=norm)

        if prediction is not None:
            ax[4].axis(axes_visibility)
            ax[4].title.set_text("Predicted Mask")
            ax[4].imshow(prediction, cmap="jet", norm=norm)

        cmap = plt.get_cmap("jet")
        legend_data = []
        for i, _ in enumerate(range(num_classes)):
            class_name = class_names[i] if class_names else str(i)
            data = [i, cmap(norm(i)), class_name]
            legend_data.append(data)
        handles = [Rectangle((0, 0), 1, 1, color=tuple(v for v in c)) for k, c, n in legend_data]
        labels = [n for k, c, n in legend_data]
        ax[0].legend(handles, labels, loc="center")
        if suptitle is not None:
            plt.suptitle(suptitle)
        return fig

__init__(data_root, num_classes, label_data_root=None, image_grep='*', label_grep='*', split=None, image_modalities=None, rgb_modality=None, rgb_indices=None, allow_missing_modalities=False, allow_substring_file_names=False, dataset_bands=None, output_bands=None, class_names=None, constant_scale=1.0, transform=None, no_data_replace=None, no_label_replace=-1, expand_temporal_dimension=False, reduce_zero_label=False, channel_position=-3, concat_bands=False, *args, **kwargs) #

Constructor

Parameters:

Name Type Description Default
data_root dict[Path]

Dictionary of paths to data root directory or csv/parquet files with image-level data, with modalities as keys.

required
num_classes int

Number of classes.

required
label_data_root Path

Path to data root directory with mask files. Set to None for prediction mode.

None
image_grep dict[str]

Dictionary with regular expression appended to data_root to find input images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
label_grep str

Regular expression appended to label_data_root to find mask files. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
split Path

Path to file containing samples prefixes to be used for this split. The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise, files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]). If not specified, search samples based on files in data_root. Defaults to None.

None
image_modalities(list[str], optional

List of pixel-level raster modalities. Defaults to data_root.keys(). The difference between all modalities and image_modalities are non-image modalities which are treated differently during the transforms and are not modified but only converted into a tensor if possible.

required
rgb_modality str

Modality used for RGB plots. Defaults to first modality in data_root.keys().

None
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
allow_missing_modalities bool

Allow missing modalities during data loading. Defaults to False.

False
allow_substring_file_names bool

Allow substrings during sample identification by adding image or label grep to the sample prefixes. If False, treats sample prefixes as full file names. If True and no split file is provided, considers the file stem as prefix, otherwise the full file name. Defaults to True.

False
dataset_bands dict[list]

Bands present in the dataset, provided in a dictionary with modalities as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset of all modalities. Defaults to None.

None
output_bands dict[list]

Bands that should be output by the dataset as named by dataset_bands, provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.

None
class_names list[str]

Names of the classes. Defaults to None.

None
constant_scale dict[float]

Factor to multiply data values by, provided as a dictionary with modalities as keys. Can be subset of all modalities. Defaults to None.

1.0
transform Compose | dict | None

Albumentations transform to be applied to all image modalities (transformation are shared between image modalities, e.g., similar crop or rotation). Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. The transform is not applied to non-image data, which is only converted to tensors if possible. If dict, can include multiple transforms per modality which are applied separately (no shared parameters between modalities). Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input data with this value. If None, does no replacement. Defaults to None.

None
no_label_replace float | None

Replace nan values in label with this value. If none, does no replacement. Defaults to -1.

-1
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Only works with image modalities. Is only applied to modalities with defined dataset_bands. Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
channel_position int

Position of the channel dimension in the image modalities. Defaults to -3.

-3
concat_bands bool

Concatenate all image modalities along the band dimension into a single "image", so that it can be processed by single-modal models. Concatenate in the order of provided modalities. Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.

False
Source code in terratorch/datasets/generic_multimodal_dataset.py
def __init__(
    self,
    data_root: Path,
    num_classes: int,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    image_modalities: list[str] | None = None,
    rgb_modality: str | None = None,
    rgb_indices: list[str] | None = None,
    allow_missing_modalities: bool = False,
    allow_substring_file_names: bool = False,
    dataset_bands: dict[list] | None = None,
    output_bands: dict[list] | None = None,
    class_names: list[str] | None = None,
    constant_scale: dict[float] = 1.0,
    transform: A.Compose | None = None,
    no_data_replace: float | None = None,
    no_label_replace: int | None = -1,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
    channel_position: int = -3,
    concat_bands: bool = False,
    *args,
    **kwargs,
) -> None:
    """Constructor

    Args:
        data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
            data, with modalities as keys.
        num_classes (int): Number of classes.
        label_data_root (Path): Path to data root directory with mask files. Set to None for prediction mode.
        image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
            images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
        label_grep (str, optional): Regular expression appended to label_data_root to find mask files.
            Defaults to "*". Ignored when allow_substring_file_names is False.
        split (Path, optional): Path to file containing samples prefixes to be used for this split.
            The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
            sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
            files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
            If not specified, search samples based on files in data_root. Defaults to None.
        image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
            The difference between all modalities and image_modalities are non-image modalities which are treated
            differently during the transforms and are not modified but only converted into a tensor if possible.
        rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
        allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
            image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
            If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
            Defaults to True.
        dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
            as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
            that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
            of all modalities. Defaults to None.
        output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
            provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
        class_names (list[str], optional): Names of the classes. Defaults to None.
        constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
            keys. Can be subset of all modalities. Defaults to None.
        transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
            modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
            Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
            Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
            converted to tensors if possible. If dict, can include multiple transforms per modality which are
            applied separately (no shared parameters between modalities).
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input data with this value.
            If None, does no replacement. Defaults to None.
        no_label_replace (float | None): Replace nan values in label with this value.
            If none, does no replacement. Defaults to -1.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Only works with image modalities. Is only applied to modalities with defined dataset_bands.
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
        channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
        concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
            that it can be processed by single-modal models. Concatenate in the order of provided modalities.
            Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
    """

    super().__init__(
        data_root,
        label_data_root=label_data_root,
        image_grep=image_grep,
        label_grep=label_grep,
        split=split,
        image_modalities=image_modalities,
        rgb_modality=rgb_modality,
        rgb_indices=rgb_indices,
        allow_missing_modalities=allow_missing_modalities,
        allow_substring_file_names=allow_substring_file_names,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        no_label_replace=no_label_replace,
        expand_temporal_dimension=expand_temporal_dimension,
        reduce_zero_label=reduce_zero_label,
        channel_position=channel_position,
        concat_bands=concat_bands,
        *args,
        **kwargs,
    )
    self.num_classes = num_classes
    self.class_names = class_names

plot(sample, suptitle=None, show_axes=False) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None
show_axes bool | None

whether to show axes or not

False

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_multimodal_dataset.py
def plot(
    self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample: a sample returned by :meth:`__getitem__`
        suptitle: optional string to use as a suptitle
        show_axes: whether to show axes or not

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """
    image = sample["image"]
    if isinstance(image, dict):
        image = image[self.rgb_modality]
    if isinstance(image, torch.Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    label_mask = sample["mask"]
    if isinstance(label_mask, torch.Tensor):
        label_mask = label_mask.numpy()

    showing_predictions = "prediction" in sample
    if showing_predictions:
        prediction_mask = sample["prediction"]
        if isinstance(prediction_mask, torch.Tensor):
            prediction_mask = prediction_mask.numpy()

    return self._plot_sample(
        image,
        label_mask,
        self.num_classes,
        prediction=prediction_mask if showing_predictions else None,
        suptitle=suptitle,
        class_names=self.class_names,
        show_axes=show_axes,
    )

terratorch.datasets.generic_multimodal_dataset.GenericMultimodalPixelwiseRegressionDataset #

Bases: GenericMultimodalDataset

GenericNonGeoPixelwiseRegressionDataset

Source code in terratorch/datasets/generic_multimodal_dataset.py
class GenericMultimodalPixelwiseRegressionDataset(GenericMultimodalDataset):
    """GenericNonGeoPixelwiseRegressionDataset"""

    def __init__(
        self,
        data_root: Path,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        image_modalities: list[str] | None = None,
        rgb_modality: str | None = None,
        rgb_indices: list[int] | None = None,
        allow_missing_modalities: bool = False,
        allow_substring_file_names: bool = False,
        dataset_bands: dict[list] | None = None,
        output_bands: dict[list] | None = None,
        constant_scale: dict[float] = 1.0,
        transform: A.Compose | dict | None = None,
        no_data_replace: float | None = None,
        no_label_replace: float | None = None,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
        channel_position: int = -3,
        concat_bands: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """Constructor

        Args:
            data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
                data, with modalities as keys.
            label_data_root (Path): Path to data root directory with ground truth files. Set to None for predictions.
            image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
                images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
            label_grep (str, optional): Regular expression appended to label_data_root to find ground truth files.
                Defaults to "*". Ignored when allow_substring_file_names is False.
            split (Path, optional): Path to file containing samples prefixes to be used for this split.
                The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
                sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
                files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
                If not specified, search samples based on files in data_root. Defaults to None.
            image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
                The difference between all modalities and image_modalities are non-image modalities which are treated
                differently during the transforms and are not modified but only converted into a tensor if possible.
            rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
            allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
                image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
                If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
                Defaults to True.
            dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
                as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
                that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
                of all modalities. Defaults to None.
            output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
                provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
            constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
                keys. Can be subset of all modalities. Defaults to None.
            transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
                modalities. Should end with ToTensorV2() and not include normalization. The transform is not applied to
                non-image data, which is only converted to tensors if possible. If dict, can include separate transforms
                per modality (no shared parameters between modalities).
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input data with this value.
                If None, does no replacement. Defaults to None.
            no_label_replace (float | None): Replace nan values in label with this value.
                If none, does no replacement. Defaults to None.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Only works with image modalities. Is only applied to modalities with defined dataset_bands.
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
            channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
            concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
                that it can be processed by single-modal models. Concatenate in the order of provided modalities.
                Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
        """

        super().__init__(
            data_root,
            label_data_root=label_data_root,
            image_grep=image_grep,
            label_grep=label_grep,
            split=split,
            image_modalities=image_modalities,
            rgb_modality=rgb_modality,
            rgb_indices=rgb_indices,
            allow_missing_modalities=allow_missing_modalities,
            allow_substring_file_names=allow_substring_file_names,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            no_label_replace=no_label_replace,
            expand_temporal_dimension=expand_temporal_dimension,
            reduce_zero_label=reduce_zero_label,
            channel_position=channel_position,
            concat_bands=concat_bands,
            *args,
            **kwargs,
        )

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)

        if "mask" in item:
            item["mask"] = item["mask"].float()

        return item

    def plot(
        self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
    ) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
            suptitle (str|None): optional string to use as a suptitle
            show_axes (bool|None): whether to show axes or not

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """

        image = sample["image"]
        if isinstance(image, dict):
            image = image[self.rgb_modality]
        if isinstance(image, torch.Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        label_mask = sample["mask"]
        if isinstance(label_mask, torch.Tensor):
            label_mask = label_mask.numpy()

        showing_predictions = "prediction" in sample
        if showing_predictions:
            prediction_mask = sample["prediction"]
            if isinstance(prediction_mask, torch.Tensor):
                prediction_mask = prediction_mask.numpy()

        return self._plot_sample(
            image,
            label_mask,
            prediction=prediction_mask if showing_predictions else None,
            suptitle=suptitle,
            show_axes=show_axes,
        )

    @staticmethod
    def _plot_sample(image, label, prediction=None, suptitle=None, show_axes=False):
        num_images = 4 if prediction is not None else 3
        fig, ax = plt.subplots(1, num_images, figsize=(12, 10), layout="compressed")
        axes_visibility = "on" if show_axes else "off"

        norm = mpl.colors.Normalize(vmin=label.min(), vmax=label.max())
        ax[0].axis(axes_visibility)
        ax[0].title.set_text("Image")
        ax[0].imshow(image)

        ax[1].axis(axes_visibility)
        ax[1].title.set_text("Ground Truth Mask")
        ax[1].imshow(label, cmap="Greens", norm=norm)

        ax[2].axis(axes_visibility)
        ax[2].title.set_text("GT Mask on Image")
        ax[2].imshow(image)
        ax[2].imshow(label, cmap="Greens", alpha=0.3, norm=norm)
        # ax[2].legend()

        if prediction is not None:
            ax[3].axis(axes_visibility)
            ax[3].title.set_text("Predicted Mask")
            ax[3].imshow(prediction, cmap="Greens", norm=norm)

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

__init__(data_root, label_data_root=None, image_grep='*', label_grep='*', split=None, image_modalities=None, rgb_modality=None, rgb_indices=None, allow_missing_modalities=False, allow_substring_file_names=False, dataset_bands=None, output_bands=None, constant_scale=1.0, transform=None, no_data_replace=None, no_label_replace=None, expand_temporal_dimension=False, reduce_zero_label=False, channel_position=-3, concat_bands=False, *args, **kwargs) #

Constructor

Parameters:

Name Type Description Default
data_root dict[Path]

Dictionary of paths to data root directory or csv/parquet files with image-level data, with modalities as keys.

required
label_data_root Path

Path to data root directory with ground truth files. Set to None for predictions.

None
image_grep dict[str]

Dictionary with regular expression appended to data_root to find input images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
label_grep str

Regular expression appended to label_data_root to find ground truth files. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
split Path

Path to file containing samples prefixes to be used for this split. The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise, files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]). If not specified, search samples based on files in data_root. Defaults to None.

None
image_modalities(list[str], optional

List of pixel-level raster modalities. Defaults to data_root.keys(). The difference between all modalities and image_modalities are non-image modalities which are treated differently during the transforms and are not modified but only converted into a tensor if possible.

required
rgb_modality str

Modality used for RGB plots. Defaults to first modality in data_root.keys().

None
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
allow_missing_modalities bool

Allow missing modalities during data loading. Defaults to False.

False
allow_substring_file_names bool

Allow substrings during sample identification by adding image or label grep to the sample prefixes. If False, treats sample prefixes as full file names. If True and no split file is provided, considers the file stem as prefix, otherwise the full file name. Defaults to True.

False
dataset_bands dict[list]

Bands present in the dataset, provided in a dictionary with modalities as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset of all modalities. Defaults to None.

None
output_bands dict[list]

Bands that should be output by the dataset as named by dataset_bands, provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.

None
constant_scale dict[float]

Factor to multiply data values by, provided as a dictionary with modalities as keys. Can be subset of all modalities. Defaults to None.

1.0
transform Compose | dict | None

Albumentations transform to be applied to all image modalities. Should end with ToTensorV2() and not include normalization. The transform is not applied to non-image data, which is only converted to tensors if possible. If dict, can include separate transforms per modality (no shared parameters between modalities). Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input data with this value. If None, does no replacement. Defaults to None.

None
no_label_replace float | None

Replace nan values in label with this value. If none, does no replacement. Defaults to None.

None
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Only works with image modalities. Is only applied to modalities with defined dataset_bands. Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
channel_position int

Position of the channel dimension in the image modalities. Defaults to -3.

-3
concat_bands bool

Concatenate all image modalities along the band dimension into a single "image", so that it can be processed by single-modal models. Concatenate in the order of provided modalities. Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.

False
Source code in terratorch/datasets/generic_multimodal_dataset.py
def __init__(
    self,
    data_root: Path,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    image_modalities: list[str] | None = None,
    rgb_modality: str | None = None,
    rgb_indices: list[int] | None = None,
    allow_missing_modalities: bool = False,
    allow_substring_file_names: bool = False,
    dataset_bands: dict[list] | None = None,
    output_bands: dict[list] | None = None,
    constant_scale: dict[float] = 1.0,
    transform: A.Compose | dict | None = None,
    no_data_replace: float | None = None,
    no_label_replace: float | None = None,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
    channel_position: int = -3,
    concat_bands: bool = False,
    *args,
    **kwargs,
) -> None:
    """Constructor

    Args:
        data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
            data, with modalities as keys.
        label_data_root (Path): Path to data root directory with ground truth files. Set to None for predictions.
        image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
            images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
        label_grep (str, optional): Regular expression appended to label_data_root to find ground truth files.
            Defaults to "*". Ignored when allow_substring_file_names is False.
        split (Path, optional): Path to file containing samples prefixes to be used for this split.
            The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
            sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
            files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
            If not specified, search samples based on files in data_root. Defaults to None.
        image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
            The difference between all modalities and image_modalities are non-image modalities which are treated
            differently during the transforms and are not modified but only converted into a tensor if possible.
        rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
        allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
            image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
            If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
            Defaults to True.
        dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
            as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
            that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
            of all modalities. Defaults to None.
        output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
            provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
        constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
            keys. Can be subset of all modalities. Defaults to None.
        transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
            modalities. Should end with ToTensorV2() and not include normalization. The transform is not applied to
            non-image data, which is only converted to tensors if possible. If dict, can include separate transforms
            per modality (no shared parameters between modalities).
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input data with this value.
            If None, does no replacement. Defaults to None.
        no_label_replace (float | None): Replace nan values in label with this value.
            If none, does no replacement. Defaults to None.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Only works with image modalities. Is only applied to modalities with defined dataset_bands.
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
        channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
        concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
            that it can be processed by single-modal models. Concatenate in the order of provided modalities.
            Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
    """

    super().__init__(
        data_root,
        label_data_root=label_data_root,
        image_grep=image_grep,
        label_grep=label_grep,
        split=split,
        image_modalities=image_modalities,
        rgb_modality=rgb_modality,
        rgb_indices=rgb_indices,
        allow_missing_modalities=allow_missing_modalities,
        allow_substring_file_names=allow_substring_file_names,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        no_label_replace=no_label_replace,
        expand_temporal_dimension=expand_temporal_dimension,
        reduce_zero_label=reduce_zero_label,
        channel_position=channel_position,
        concat_bands=concat_bands,
        *args,
        **kwargs,
    )

plot(sample, suptitle=None, show_axes=False) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None
show_axes bool | None

whether to show axes or not

False

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_multimodal_dataset.py
def plot(
    self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
        suptitle (str|None): optional string to use as a suptitle
        show_axes (bool|None): whether to show axes or not

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """

    image = sample["image"]
    if isinstance(image, dict):
        image = image[self.rgb_modality]
    if isinstance(image, torch.Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    label_mask = sample["mask"]
    if isinstance(label_mask, torch.Tensor):
        label_mask = label_mask.numpy()

    showing_predictions = "prediction" in sample
    if showing_predictions:
        prediction_mask = sample["prediction"]
        if isinstance(prediction_mask, torch.Tensor):
            prediction_mask = prediction_mask.numpy()

    return self._plot_sample(
        image,
        label_mask,
        prediction=prediction_mask if showing_predictions else None,
        suptitle=suptitle,
        show_axes=show_axes,
    )

terratorch.datasets.generic_multimodal_dataset.GenericMultimodalScalarDataset #

Bases: GenericMultimodalDataset

GenericMultimodalClassificationDataset

Source code in terratorch/datasets/generic_multimodal_dataset.py
class GenericMultimodalScalarDataset(GenericMultimodalDataset):
    """GenericMultimodalClassificationDataset"""

    def __init__(
        self,
        data_root: Path,
        num_classes: int,
        label_data_root: Path | None = None,
        image_grep: str | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        image_modalities: list[str] | None = None,
        rgb_modality: str | None = None,
        rgb_indices: list[int] | None = None,
        allow_missing_modalities: bool = False,
        allow_substring_file_names: bool = False,
        dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
        class_names: list[str] | None = None,
        constant_scale: dict[float] = 1.0,
        transform: A.Compose | None = None,
        no_data_replace: float | None = None,
        no_label_replace: int | None = None,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
        channel_position: int = -3,
        concat_bands: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """Constructor

        Args:
            data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
                data, with modalities as keys.
            num_classes (int): Number of classes.
            label_data_root (Path, optional): Path to data root directory with labels or csv/parquet files with labels.
                Set to None for prediction mode.
            image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
                images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
            label_grep (str, optional): Regular expression appended to label_data_root to find labels files.
                Defaults to "*". Ignored when allow_substring_file_names is False.
            split (Path, optional): Path to file containing samples prefixes to be used for this split.
                The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
                sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
                files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
                If not specified, search samples based on files in data_root. Defaults to None.
            image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
                The difference between all modalities and image_modalities are non-image modalities which are treated
                differently during the transforms and are not modified but only converted into a tensor if possible.
            rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
            allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
                image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
                If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
                Defaults to True.
            dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
                as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
                that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
                of all modalities. Defaults to None.
            output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
                provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
            class_names (list[str], optional): Names of the classes. Defaults to None.
            constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
                keys. Can be subset of all modalities. Defaults to None.
            transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
                modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
                Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
                Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
                converted to tensors if possible. If dict, can include multiple transforms per modality which are
                applied separately (no shared parameters between modalities).
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input data with this value.
                If None, does no replacement. Defaults to None.
            no_label_replace (float | None): Replace nan values in label with this value.
                If none, does no replacement. Defaults to -1.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Only works with image modalities. Is only applied to modalities with defined dataset_bands.
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
            channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
            concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
                that it can be processed by single-modal models. Concatenate in the order of provided modalities.
                Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
        """

        super().__init__(
            data_root,
            label_data_root=label_data_root,
            image_grep=image_grep,
            label_grep=label_grep,
            split=split,
            image_modalities=image_modalities,
            rgb_modality=rgb_modality,
            rgb_indices=rgb_indices,
            allow_missing_modalities=allow_missing_modalities,
            allow_substring_file_names=allow_substring_file_names,
            dataset_bands=dataset_bands,
            output_bands=output_bands,
            constant_scale=constant_scale,
            transform=transform,
            no_data_replace=no_data_replace,
            no_label_replace=no_label_replace,
            expand_temporal_dimension=expand_temporal_dimension,
            reduce_zero_label=reduce_zero_label,
            channel_position=channel_position,
            scalar_label=True,
            concat_bands=concat_bands,
            *args,
            **kwargs,
        )

        self.num_classes = num_classes
        self.class_names = class_names

    def __getitem__(self, index: int) -> dict[str, Any]:
        item = super().__getitem__(index)
        return item

    def plot(
        self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
    ) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
            suptitle (str|None): optional string to use as a suptitle
            show_axes (bool|None): whether to show axes or not

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """

        # TODO: Check plotting code for classification tasks and add it to generic classification dataset as well
        raise NotImplementedError

        image = sample["image"]
        if isinstance(image, dict):
            image = image[self.rgb_modality]
        if isinstance(image, torch.Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        label_mask = sample["mask"]
        if isinstance(label_mask, torch.Tensor):
            label_mask = label_mask.numpy()

        showing_predictions = "prediction" in sample
        if showing_predictions:
            prediction_mask = sample["prediction"]
            if isinstance(prediction_mask, torch.Tensor):
                prediction_mask = prediction_mask.numpy()

        return self._plot_sample(
            image,
            label_mask,
            prediction=prediction_mask if showing_predictions else None,
            suptitle=suptitle,
            show_axes=show_axes,
        )

    @staticmethod
    def _plot_sample(image, label, prediction=None, suptitle=None, show_axes=False):
        num_images = 4 if prediction is not None else 3
        fig, ax = plt.subplots(1, num_images, figsize=(12, 10), layout="compressed")
        axes_visibility = "on" if show_axes else "off"

        norm = mpl.colors.Normalize(vmin=label.min(), vmax=label.max())
        ax[0].axis(axes_visibility)
        ax[0].title.set_text("Image")
        ax[0].imshow(image)

        ax[1].axis(axes_visibility)
        ax[1].title.set_text("Ground Truth Mask")
        ax[1].imshow(label, cmap="Greens", norm=norm)

        ax[2].axis(axes_visibility)
        ax[2].title.set_text("GT Mask on Image")
        ax[2].imshow(image)
        ax[2].imshow(label, cmap="Greens", alpha=0.3, norm=norm)
        # ax[2].legend()

        if prediction is not None:
            ax[3].axis(axes_visibility)
            ax[3].title.set_text("Predicted Mask")
            ax[3].imshow(prediction, cmap="Greens", norm=norm)

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

__init__(data_root, num_classes, label_data_root=None, image_grep='*', label_grep='*', split=None, image_modalities=None, rgb_modality=None, rgb_indices=None, allow_missing_modalities=False, allow_substring_file_names=False, dataset_bands=None, output_bands=None, class_names=None, constant_scale=1.0, transform=None, no_data_replace=None, no_label_replace=None, expand_temporal_dimension=False, reduce_zero_label=False, channel_position=-3, concat_bands=False, *args, **kwargs) #

Constructor

Parameters:

Name Type Description Default
data_root dict[Path]

Dictionary of paths to data root directory or csv/parquet files with image-level data, with modalities as keys.

required
num_classes int

Number of classes.

required
label_data_root Path

Path to data root directory with labels or csv/parquet files with labels. Set to None for prediction mode.

None
image_grep dict[str]

Dictionary with regular expression appended to data_root to find input images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
label_grep str

Regular expression appended to label_data_root to find labels files. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
split Path

Path to file containing samples prefixes to be used for this split. The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise, files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]). If not specified, search samples based on files in data_root. Defaults to None.

None
image_modalities(list[str], optional

List of pixel-level raster modalities. Defaults to data_root.keys(). The difference between all modalities and image_modalities are non-image modalities which are treated differently during the transforms and are not modified but only converted into a tensor if possible.

required
rgb_modality str

Modality used for RGB plots. Defaults to first modality in data_root.keys().

None
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
allow_missing_modalities bool

Allow missing modalities during data loading. Defaults to False.

False
allow_substring_file_names bool

Allow substrings during sample identification by adding image or label grep to the sample prefixes. If False, treats sample prefixes as full file names. If True and no split file is provided, considers the file stem as prefix, otherwise the full file name. Defaults to True.

False
dataset_bands dict[list]

Bands present in the dataset, provided in a dictionary with modalities as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset of all modalities. Defaults to None.

None
output_bands dict[list]

Bands that should be output by the dataset as named by dataset_bands, provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.

None
class_names list[str]

Names of the classes. Defaults to None.

None
constant_scale dict[float]

Factor to multiply data values by, provided as a dictionary with modalities as keys. Can be subset of all modalities. Defaults to None.

1.0
transform Compose | dict | None

Albumentations transform to be applied to all image modalities (transformation are shared between image modalities, e.g., similar crop or rotation). Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. The transform is not applied to non-image data, which is only converted to tensors if possible. If dict, can include multiple transforms per modality which are applied separately (no shared parameters between modalities). Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input data with this value. If None, does no replacement. Defaults to None.

None
no_label_replace float | None

Replace nan values in label with this value. If none, does no replacement. Defaults to -1.

None
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Only works with image modalities. Is only applied to modalities with defined dataset_bands. Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
channel_position int

Position of the channel dimension in the image modalities. Defaults to -3.

-3
concat_bands bool

Concatenate all image modalities along the band dimension into a single "image", so that it can be processed by single-modal models. Concatenate in the order of provided modalities. Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.

False
Source code in terratorch/datasets/generic_multimodal_dataset.py
def __init__(
    self,
    data_root: Path,
    num_classes: int,
    label_data_root: Path | None = None,
    image_grep: str | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    image_modalities: list[str] | None = None,
    rgb_modality: str | None = None,
    rgb_indices: list[int] | None = None,
    allow_missing_modalities: bool = False,
    allow_substring_file_names: bool = False,
    dataset_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    output_bands: list[HLSBands | int | tuple[int, int] | str] | None = None,
    class_names: list[str] | None = None,
    constant_scale: dict[float] = 1.0,
    transform: A.Compose | None = None,
    no_data_replace: float | None = None,
    no_label_replace: int | None = None,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
    channel_position: int = -3,
    concat_bands: bool = False,
    *args,
    **kwargs,
) -> None:
    """Constructor

    Args:
        data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
            data, with modalities as keys.
        num_classes (int): Number of classes.
        label_data_root (Path, optional): Path to data root directory with labels or csv/parquet files with labels.
            Set to None for prediction mode.
        image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
            images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
        label_grep (str, optional): Regular expression appended to label_data_root to find labels files.
            Defaults to "*". Ignored when allow_substring_file_names is False.
        split (Path, optional): Path to file containing samples prefixes to be used for this split.
            The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
            sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
            files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
            If not specified, search samples based on files in data_root. Defaults to None.
        image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
            The difference between all modalities and image_modalities are non-image modalities which are treated
            differently during the transforms and are not modified but only converted into a tensor if possible.
        rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
        allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
            image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
            If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
            Defaults to True.
        dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
            as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
            that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
            of all modalities. Defaults to None.
        output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
            provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
        class_names (list[str], optional): Names of the classes. Defaults to None.
        constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
            keys. Can be subset of all modalities. Defaults to None.
        transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
            modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
            Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
            Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
            converted to tensors if possible. If dict, can include multiple transforms per modality which are
            applied separately (no shared parameters between modalities).
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input data with this value.
            If None, does no replacement. Defaults to None.
        no_label_replace (float | None): Replace nan values in label with this value.
            If none, does no replacement. Defaults to -1.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Only works with image modalities. Is only applied to modalities with defined dataset_bands.
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
        channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
        concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
            that it can be processed by single-modal models. Concatenate in the order of provided modalities.
            Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
    """

    super().__init__(
        data_root,
        label_data_root=label_data_root,
        image_grep=image_grep,
        label_grep=label_grep,
        split=split,
        image_modalities=image_modalities,
        rgb_modality=rgb_modality,
        rgb_indices=rgb_indices,
        allow_missing_modalities=allow_missing_modalities,
        allow_substring_file_names=allow_substring_file_names,
        dataset_bands=dataset_bands,
        output_bands=output_bands,
        constant_scale=constant_scale,
        transform=transform,
        no_data_replace=no_data_replace,
        no_label_replace=no_label_replace,
        expand_temporal_dimension=expand_temporal_dimension,
        reduce_zero_label=reduce_zero_label,
        channel_position=channel_position,
        scalar_label=True,
        concat_bands=concat_bands,
        *args,
        **kwargs,
    )

    self.num_classes = num_classes
    self.class_names = class_names

plot(sample, suptitle=None, show_axes=False) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None
show_axes bool | None

whether to show axes or not

False

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_multimodal_dataset.py
def plot(
    self, sample: dict[str, torch.Tensor], suptitle: str | None = None, show_axes: bool | None = False
) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample (dict[str, Tensor]): a sample returned by :meth:`__getitem__`
        suptitle (str|None): optional string to use as a suptitle
        show_axes (bool|None): whether to show axes or not

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """

    # TODO: Check plotting code for classification tasks and add it to generic classification dataset as well
    raise NotImplementedError

    image = sample["image"]
    if isinstance(image, dict):
        image = image[self.rgb_modality]
    if isinstance(image, torch.Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    label_mask = sample["mask"]
    if isinstance(label_mask, torch.Tensor):
        label_mask = label_mask.numpy()

    showing_predictions = "prediction" in sample
    if showing_predictions:
        prediction_mask = sample["prediction"]
        if isinstance(prediction_mask, torch.Tensor):
            prediction_mask = prediction_mask.numpy()

    return self._plot_sample(
        image,
        label_mask,
        prediction=prediction_mask if showing_predictions else None,
        suptitle=suptitle,
        show_axes=show_axes,
    )

terratorch.datasets.generic_multimodal_dataset.GenericMultimodalDataset #

Bases: NonGeoDataset, ABC

This is a generic dataset class to be used for instantiating datasets from arguments. Ideally, one would create a dataset class specific to a dataset.

Source code in terratorch/datasets/generic_multimodal_dataset.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
class GenericMultimodalDataset(NonGeoDataset, ABC):
    """
    This is a generic dataset class to be used for instantiating datasets from arguments.
    Ideally, one would create a dataset class specific to a dataset.
    """

    def __init__(
        self,
        data_root: dict[str, Path | str],
        label_data_root: Path | str | list[Path | str] | None = None,
        image_grep: dict[str, str] | None = "*",
        label_grep: str | None = "*",
        split: Path | None = None,
        image_modalities: list[str] | None = None,
        rgb_modality: str | None = None,
        rgb_indices: list[int] | None = None,
        allow_missing_modalities: bool = False,
        allow_substring_file_names: bool = True,
        dataset_bands: dict[str, list] | None = None,
        output_bands: dict[str, list] | None = None,
        constant_scale: dict[str, float] = None,
        transform: A.Compose | dict | None = None,
        no_data_replace: float | None = None,
        no_label_replace: float | None = -1,
        expand_temporal_dimension: bool = False,
        reduce_zero_label: bool = False,
        channel_position: int = -3,
        scalar_label: bool = False,
        data_with_sample_dim: bool = False,
        concat_bands: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """Constructor

        Args:
            data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
                data, with modalities as keys.
            label_data_root (Path, optional): Path to data root directory with labels or csv/parquet files with
                image-level labels. Needs to be specified for supervised tasks. Set to None for prediction mode.
            image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
                images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
            label_grep (str, optional): Regular expression appended to label_data_root to find labels or mask files.
                Defaults to "*". Ignored when allow_substring_file_names is False.
            split (Path, optional): Path to file containing samples prefixes to be used for this split.
                The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
                sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
                files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
                If not specified, search samples based on files in data_root. Defaults to None.
            image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
                The difference between all modalities and image_modalities are non-image modalities which are treated
                differently during the transforms and are not modified but only converted into a tensor if possible.
            rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
            rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
            allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
            allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
                image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
                If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
                Defaults to True.
            dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
                as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
                that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
                of all modalities. Defaults to None.
            output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
                provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
            constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
                keys. Can be subset of all modalities. Defaults to None.
            transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
                modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
                Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
                Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
                converted to tensors if possible. If dict, can include multiple transforms per modality which are
                applied separately (no shared parameters between modalities).
                Defaults to None, which simply applies ToTensorV2().
            no_data_replace (float | None): Replace nan values in input data with this value.
                If None, does no replacement. Defaults to None.
            no_label_replace (float | None): Replace nan values in label with this value.
                If none, does no replacement. Defaults to -1.
            expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
                Only works with image modalities. Is only applied to modalities with defined dataset_bands.
                Defaults to False.
            reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
                expected 0. Defaults to False.
            channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
            scalar_label (bool): Returns a image mask if False or otherwise the raw labels. Defaults to False.
            concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
                that it can be processed by single-modal models. Concatenate in the order of provided modalities.
                Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
        """

        super().__init__()

        self.split_file = split
        self.modalities = list(data_root.keys())
        assert "mask" not in self.modalities, "Modality cannot be called 'mask'."
        self.image_modalities = image_modalities or self.modalities
        self.non_image_modalities = list(set(self.modalities) - set(image_modalities))
        self.modalities = self.image_modalities + self.non_image_modalities  # Ensure image modalities to be first

        if scalar_label:
            self.non_image_modalities += ["label"]

        # Order by modalities and convert path strings to lists as the code expects a list of paths per modality
        data_root = {m: data_root[m] for m in self.modalities}

        self.constant_scale = constant_scale or {}
        self.no_data_replace = no_data_replace
        self.no_label_replace = no_label_replace
        self.reduce_zero_label = reduce_zero_label
        self.expand_temporal_dimension = expand_temporal_dimension
        self.channel_position = channel_position
        self.scalar_label = scalar_label
        self.data_with_sample_dim = data_with_sample_dim
        self.concat_bands = concat_bands
        assert not self.concat_bands or len(self.non_image_modalities) == 0, (
            f"concat_bands can only be used with image modalities, "
            f"but non-image modalities are given: {self.non_image_modalities}"
        )
        assert (
            not self.concat_bands or not allow_missing_modalities
        ), "concat_bands cannot be used with allow_missing_modalities."

        if self.expand_temporal_dimension and dataset_bands is None:
            msg = "Please provide dataset_bands when expand_temporal_dimension is True"
            raise Exception(msg)

        # Load samples based on split file
        if self.split_file is not None:
            if str(self.split_file).endswith(".txt"):
                with open(self.split_file) as f:
                    split = f.readlines()
                valid_files = [rf"{substring.strip()}" for substring in split]
            else:
                valid_files = list(load_table_data(self.split_file).index)

        else:
            image_files = {}
            for m, m_paths in data_root.items():
                image_files[m] = sorted(glob.glob(os.path.join(m_paths, image_grep[m])))

            def get_file_id(file_name, mod):
                glob_as_regex = '^' + ''.join('(.*?)' if ch == '*' else re.escape(ch)
                                              for ch in image_grep[mod]) + '$'
                stem = re.match(glob_as_regex, os.path.basename(file_name)).group(1)
                if allow_substring_file_names:
                    # Remove file extensions
                    stem = os.path.splitext(stem)[0]
                return stem

            if allow_missing_modalities:
                valid_files = list(set([get_file_id(file, mod)
                                        for mod, files in image_files.items()
                                        for file in files
                                        ]))
            else:
                valid_files = [get_file_id(file, self.modalities[0]) for file in image_files[self.modalities[0]]]

        self.samples = []
        num_modalities = len(self.modalities) + int(label_data_root is not None)

        # Check for parquet and csv files with modality data and read the file

        for m, m_path in data_root.items():
            if os.path.isfile(m_path):
                data_root[m] = load_table_data(m_path)
                # Check for some sample keys
                if not any(f in data_root[m].index for f in valid_files[:100]):
                    warnings.warn(f"Sample key expected in table index (first column) for {m} (file: {m_path}). "
                                  f"{valid_files[:3]+['...']} are not in index {list(data_root[m].index[:3])+['...']}.")
        if label_data_root is not None:
            if os.path.isfile(label_data_root):
                label_data_root = load_table_data(label_data_root)
                # Check for some sample keys
                if not any(f in label_data_root.index for f in valid_files[:100]):
                    warnings.warn(f"Keys expected in table index (first column) for labels (file: {label_data_root}). "
                                  f"The keys {valid_files[:3] + ['...']} are not in the index.")

        # Iterate over all files in split
        for file in valid_files:
            sample = {}
            # Iterate over all modalities
            for m, m_path in data_root.items():
                if isinstance(m_path, pd.DataFrame):
                    # Add tabular data to sample
                    sample[m] = m_path.loc[file].values
                elif allow_substring_file_names:
                    # Substring match with image_grep
                    m_files = sorted(glob.glob(os.path.join(m_path, file + image_grep[m])))
                    if m_files:
                        sample[m] = m_files[-1]
                        if len(m_files) > 1:
                            warnings.warn(f"Found multiple matching files for sample {file} and grep {image_grep[m]}: "
                                          f"{m_files}. Selecting last one. "
                                          f"Consider changing data structure or parameters for unique selection.")
                else:
                    # Exact match
                    file_path = os.path.join(m_path, file)
                    if os.path.exists(file_path):
                        sample[m] = file_path

            if label_data_root is not None:
                if isinstance(label_data_root, pd.DataFrame):
                    # Add tabular data to sample
                    sample["mask"] = label_data_root.loc[file].values
                elif allow_substring_file_names:
                    # Substring match with label_grep
                    l_files = sorted(glob.glob(os.path.join(label_data_root, file + label_grep)))
                    if l_files:
                        sample["mask"] = l_files[-1]
                else:
                    # Exact match
                    file_path = os.path.join(label_data_root, file)
                    if os.path.exists(file_path):
                        sample["mask"] = file_path
                if "mask" not in sample:
                    # Only add sample if mask is present
                    break

            if len(sample) == num_modalities or allow_missing_modalities:
                self.samples.append(sample)

        self.rgb_modality = rgb_modality or self.modalities[0]
        self.rgb_indices = rgb_indices or [0, 1, 2]

        if dataset_bands is not None:
            self.dataset_bands = {m: generate_bands_intervals(m_bands) for m, m_bands in dataset_bands.items()}
        else:
            self.dataset_bands = None
        if output_bands is not None:
            self.output_bands = {m: generate_bands_intervals(m_bands) for m, m_bands in output_bands.items()}
            for modality in self.modalities:
                if modality in self.output_bands and modality not in self.dataset_bands:
                    msg = f"If output bands are provided, dataset_bands must also be provided (modality: {modality})"
                    raise Exception(msg)  # noqa: PLE0101
        else:
            self.output_bands = {}

        self.filter_indices = {}
        if self.output_bands:
            for m in self.output_bands.keys():
                if m not in self.output_bands or self.output_bands[m] == self.dataset_bands[m]:
                    continue
                if len(set(self.output_bands[m]) & set(self.dataset_bands[m])) != len(self.output_bands[m]):
                    msg = f"Output bands must be a subset of dataset bands (Modality: {m})"
                    raise Exception(msg)

                self.filter_indices[m] = [self.dataset_bands[m].index(band) for band in self.output_bands[m]]

            if not self.channel_position:
                logger.warning(
                    "output_bands is defined but no channel_position is provided. "
                    "Channels must be in the last dimension, otherwise provide channel_position."
                )

        # If no transform is given, apply only to transform to torch tensor
        if isinstance(transform, A.Compose):
            self.transform = MultimodalTransforms(transform,
                                                  non_image_modalities=self.non_image_modalities + ['label']
                                                  if scalar_label else self.non_image_modalities)
        elif transform is None:
            self.transform = MultimodalToTensor(self.modalities)
        else:
            # Modality-specific transforms
            transform = {m: transform[m] if m in transform else default_transform for m in self.modalities}
            self.transform = MultimodalTransforms(transform, shared=False)

        # Ignore rasterio warning for not geo-referenced files
        import rasterio

        warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
        warnings.filterwarnings("ignore", message="Dataset has no geotransform")

    def __len__(self) -> int:
        return len(self.samples)

    def __getitem__(self, index: int) -> dict[str, Any]:
        output = {}
        if isinstance(index, tuple):
            # Load only sampled modalities instead of all modalities
            # (see sample_num_modalities in GenericMultiModalDataModule for details)
            index, modalities = index
            sample = {m: self.samples[index][m] for m in modalities}
        else:
            sample = self.samples[index]

        for modality, file in sample.items():
            data = self._load_file(
                file,
                nan_replace=self.no_label_replace if modality == "mask" else self.no_data_replace,
                modality=modality,
            )

            # Expand temporal dim
            if modality in self.filter_indices and self.expand_temporal_dimension:
                data = rearrange(
                    data, "(channels time) h w -> channels time h w", channels=len(self.dataset_bands[modality])
                )

            if modality == "mask" and not self.scalar_label:
                # tasks expect image masks without channel dim
                data = data[0]

            if modality in self.image_modalities and len(data.shape) >= 3 and self.channel_position:
                # to channels last (required by albumentations)
                data = np.moveaxis(data, self.channel_position, -1)

            if modality in self.filter_indices:
                data = data[..., self.filter_indices[modality]]

            if modality in self.constant_scale:
                data = data.astype(np.float32) * self.constant_scale[modality]

            output[modality] = data

        if "mask" in output:
            if self.reduce_zero_label:
                output["mask"] -= 1
            if self.scalar_label:
                output["label"] = output.pop("mask")

        if self.transform:
            output = self.transform(output)

        if self.concat_bands:
            # Concatenate bands of all image modalities
            data = [output.pop(m) for m in self.image_modalities if m in output]
            output["image"] = torch.cat(data, dim=1 if self.data_with_sample_dim else 0)
        else:
            # Tasks expect data to be stored in "image", moving modalities to image dict
            output["image"] = {m: output.pop(m) for m in self.modalities if m in output}

        output["filename"] = self.samples[index]

        return output

    def _load_file(self, path, nan_replace: int | float | None = None, modality: str | None = None) -> xr.DataArray:
        if isinstance(path, np.ndarray):
            # data was loaded from table and is saved in memory
            data = path
        elif path.endswith(".zarr") or path.endswith(".zarr.zip"):
            data = xr.open_zarr(path, mask_and_scale=True)
            data_var = modality if modality in data.data_vars else list(data.data_vars)[0]
            data = data[data_var].to_numpy()
        elif path.endswith(".npy"):
            data = np.load(path)
        else:
            data = rioxarray.open_rasterio(path, masked=True).to_numpy()

        if nan_replace is not None:
            data = np.nan_to_num(data, nan=nan_replace)
        return data

    def plot(self, sample: dict[str, torch.Tensor], suptitle: str | None = None) -> Figure:
        """Plot a sample from the dataset.

        Args:
            sample: a sample returned by :meth:`__getitem__`
            suptitle: optional string to use as a suptitle

        Returns:
            a matplotlib Figure with the rendered sample

        .. versionadded:: 0.2
        """
        image = sample["image"]
        if isinstance(image, dict):
            image = image[self.rgb_modality]
        if isinstance(image, torch.Tensor):
            image = image.numpy()
        image = image.take(self.rgb_indices, axis=0)
        image = np.transpose(image, (1, 2, 0))
        image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        image = np.clip(image, 0, 1)

        if "mask" in sample:
            mask = sample["mask"]
            if isinstance(mask, torch.Tensor):
                mask = mask.numpy()
            if mask.ndim == 2:
                mask = np.expand_dims(mask, axis=-1)
            # Convert masked regions to 0.
            mask = mask * -1 + 1
        else:
            mask = None

        if "prediction" in sample:
            prediction = sample["prediction"]
            if isinstance(image, dict):
                prediction = prediction[self.rgb_modality]
            if isinstance(prediction, torch.Tensor):
                prediction = prediction.numpy()
            # Assuming reconstructed image
            prediction = prediction.take(self.rgb_indices, axis=0)
            prediction = np.transpose(prediction, (1, 2, 0))
            prediction = (prediction - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
            prediction = np.clip(prediction, 0, 1)
        else:
            prediction = None

        return self._plot_sample(
            image,
            mask=mask,
            prediction=prediction,
            suptitle=suptitle,
        )

    @staticmethod
    def _plot_sample(image, mask=None, prediction=None, suptitle=None):
        num_images = 1 + int(mask is not None) + int(prediction is not None)
        fig, ax = plt.subplots(1, num_images, figsize=(5*num_images, 5), layout="compressed")

        ax[0].axis("off")
        ax[0].imshow(image)

        if mask is not None:
            ax[1].axis("off")
            ax[1].imshow(image * mask)

        if prediction is not None:
            ax[num_images-1].axis("off")
            ax[num_images-1].imshow(prediction)

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

__init__(data_root, label_data_root=None, image_grep='*', label_grep='*', split=None, image_modalities=None, rgb_modality=None, rgb_indices=None, allow_missing_modalities=False, allow_substring_file_names=True, dataset_bands=None, output_bands=None, constant_scale=None, transform=None, no_data_replace=None, no_label_replace=-1, expand_temporal_dimension=False, reduce_zero_label=False, channel_position=-3, scalar_label=False, data_with_sample_dim=False, concat_bands=False, *args, **kwargs) #

Constructor

Parameters:

Name Type Description Default
data_root dict[Path]

Dictionary of paths to data root directory or csv/parquet files with image-level data, with modalities as keys.

required
label_data_root Path

Path to data root directory with labels or csv/parquet files with image-level labels. Needs to be specified for supervised tasks. Set to None for prediction mode.

None
image_grep dict[str]

Dictionary with regular expression appended to data_root to find input images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
label_grep str

Regular expression appended to label_data_root to find labels or mask files. Defaults to "*". Ignored when allow_substring_file_names is False.

'*'
split Path

Path to file containing samples prefixes to be used for this split. The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise, files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]). If not specified, search samples based on files in data_root. Defaults to None.

None
image_modalities(list[str], optional

List of pixel-level raster modalities. Defaults to data_root.keys(). The difference between all modalities and image_modalities are non-image modalities which are treated differently during the transforms and are not modified but only converted into a tensor if possible.

required
rgb_modality str

Modality used for RGB plots. Defaults to first modality in data_root.keys().

None
rgb_indices list[str]

Indices of RGB channels. Defaults to [0, 1, 2].

None
allow_missing_modalities bool

Allow missing modalities during data loading. Defaults to False.

False
allow_substring_file_names bool

Allow substrings during sample identification by adding image or label grep to the sample prefixes. If False, treats sample prefixes as full file names. If True and no split file is provided, considers the file stem as prefix, otherwise the full file name. Defaults to True.

True
dataset_bands dict[list]

Bands present in the dataset, provided in a dictionary with modalities as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset of all modalities. Defaults to None.

None
output_bands dict[list]

Bands that should be output by the dataset as named by dataset_bands, provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.

None
constant_scale dict[float]

Factor to multiply data values by, provided as a dictionary with modalities as keys. Can be subset of all modalities. Defaults to None.

None
transform Compose | dict | None

Albumentations transform to be applied to all image modalities (transformation are shared between image modalities, e.g., similar crop or rotation). Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization. Not supported for multi-temporal data. The transform is not applied to non-image data, which is only converted to tensors if possible. If dict, can include multiple transforms per modality which are applied separately (no shared parameters between modalities). Defaults to None, which simply applies ToTensorV2().

None
no_data_replace float | None

Replace nan values in input data with this value. If None, does no replacement. Defaults to None.

None
no_label_replace float | None

Replace nan values in label with this value. If none, does no replacement. Defaults to -1.

-1
expand_temporal_dimension bool

Go from shape (time*channels, h, w) to (channels, time, h, w). Only works with image modalities. Is only applied to modalities with defined dataset_bands. Defaults to False.

False
reduce_zero_label bool

Subtract 1 from all labels. Useful when labels start from 1 instead of the expected 0. Defaults to False.

False
channel_position int

Position of the channel dimension in the image modalities. Defaults to -3.

-3
scalar_label bool

Returns a image mask if False or otherwise the raw labels. Defaults to False.

False
concat_bands bool

Concatenate all image modalities along the band dimension into a single "image", so that it can be processed by single-modal models. Concatenate in the order of provided modalities. Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.

False
Source code in terratorch/datasets/generic_multimodal_dataset.py
def __init__(
    self,
    data_root: dict[str, Path | str],
    label_data_root: Path | str | list[Path | str] | None = None,
    image_grep: dict[str, str] | None = "*",
    label_grep: str | None = "*",
    split: Path | None = None,
    image_modalities: list[str] | None = None,
    rgb_modality: str | None = None,
    rgb_indices: list[int] | None = None,
    allow_missing_modalities: bool = False,
    allow_substring_file_names: bool = True,
    dataset_bands: dict[str, list] | None = None,
    output_bands: dict[str, list] | None = None,
    constant_scale: dict[str, float] = None,
    transform: A.Compose | dict | None = None,
    no_data_replace: float | None = None,
    no_label_replace: float | None = -1,
    expand_temporal_dimension: bool = False,
    reduce_zero_label: bool = False,
    channel_position: int = -3,
    scalar_label: bool = False,
    data_with_sample_dim: bool = False,
    concat_bands: bool = False,
    *args,
    **kwargs,
) -> None:
    """Constructor

    Args:
        data_root (dict[Path]): Dictionary of paths to data root directory or csv/parquet files with image-level
            data, with modalities as keys.
        label_data_root (Path, optional): Path to data root directory with labels or csv/parquet files with
            image-level labels. Needs to be specified for supervised tasks. Set to None for prediction mode.
        image_grep (dict[str], optional): Dictionary with regular expression appended to data_root to find input
            images, with modalities as keys. Defaults to "*". Ignored when allow_substring_file_names is False.
        label_grep (str, optional): Regular expression appended to label_data_root to find labels or mask files.
            Defaults to "*". Ignored when allow_substring_file_names is False.
        split (Path, optional): Path to file containing samples prefixes to be used for this split.
            The file can be a csv/parquet file with the prefixes in the index or a txt file with new-line separated
            sample prefixes. File names must be exact matches if allow_substring_file_names is False. Otherwise,
            files are searched using glob with the form Path(data_root).glob(prefix + [image or label grep]).
            If not specified, search samples based on files in data_root. Defaults to None.
        image_modalities(list[str], optional): List of pixel-level raster modalities. Defaults to data_root.keys().
            The difference between all modalities and image_modalities are non-image modalities which are treated
            differently during the transforms and are not modified but only converted into a tensor if possible.
        rgb_modality (str, optional): Modality used for RGB plots. Defaults to first modality in data_root.keys().
        rgb_indices (list[str], optional): Indices of RGB channels. Defaults to [0, 1, 2].
        allow_missing_modalities (bool, optional): Allow missing modalities during data loading. Defaults to False.
        allow_substring_file_names (bool, optional): Allow substrings during sample identification by adding
            image or label grep to the sample prefixes. If False, treats sample prefixes as full file names.
            If True and no split file is provided, considers the file stem as prefix, otherwise the full file name.
            Defaults to True.
        dataset_bands (dict[list], optional): Bands present in the dataset, provided in a dictionary with modalities
            as keys. This parameter names input channels (bands) using HLSBands, ints, int ranges, or strings, so
            that they can then be referred to by output_bands. Needs to be superset of output_bands. Can be a subset
            of all modalities. Defaults to None.
        output_bands (dict[list], optional): Bands that should be output by the dataset as named by dataset_bands,
            provided as a dictionary with modality keys. Can be subset of all modalities. Defaults to None.
        constant_scale (dict[float]): Factor to multiply data values by, provided as a dictionary with modalities as
            keys. Can be subset of all modalities. Defaults to None.
        transform (Albumentations.Compose | dict | None): Albumentations transform to be applied to all image
            modalities (transformation are shared between image modalities, e.g., similar crop or rotation).
            Should end with ToTensorV2(). If used through the generic_data_module, should not include normalization.
            Not supported for multi-temporal data. The transform is not applied to non-image data, which is only
            converted to tensors if possible. If dict, can include multiple transforms per modality which are
            applied separately (no shared parameters between modalities).
            Defaults to None, which simply applies ToTensorV2().
        no_data_replace (float | None): Replace nan values in input data with this value.
            If None, does no replacement. Defaults to None.
        no_label_replace (float | None): Replace nan values in label with this value.
            If none, does no replacement. Defaults to -1.
        expand_temporal_dimension (bool): Go from shape (time*channels, h, w) to (channels, time, h, w).
            Only works with image modalities. Is only applied to modalities with defined dataset_bands.
            Defaults to False.
        reduce_zero_label (bool): Subtract 1 from all labels. Useful when labels start from 1 instead of the
            expected 0. Defaults to False.
        channel_position (int): Position of the channel dimension in the image modalities. Defaults to -3.
        scalar_label (bool): Returns a image mask if False or otherwise the raw labels. Defaults to False.
        concat_bands (bool): Concatenate all image modalities along the band dimension into a single "image", so
            that it can be processed by single-modal models. Concatenate in the order of provided modalities.
            Works with image modalities only. Does not work with allow_missing_modalities. Defaults to False.
    """

    super().__init__()

    self.split_file = split
    self.modalities = list(data_root.keys())
    assert "mask" not in self.modalities, "Modality cannot be called 'mask'."
    self.image_modalities = image_modalities or self.modalities
    self.non_image_modalities = list(set(self.modalities) - set(image_modalities))
    self.modalities = self.image_modalities + self.non_image_modalities  # Ensure image modalities to be first

    if scalar_label:
        self.non_image_modalities += ["label"]

    # Order by modalities and convert path strings to lists as the code expects a list of paths per modality
    data_root = {m: data_root[m] for m in self.modalities}

    self.constant_scale = constant_scale or {}
    self.no_data_replace = no_data_replace
    self.no_label_replace = no_label_replace
    self.reduce_zero_label = reduce_zero_label
    self.expand_temporal_dimension = expand_temporal_dimension
    self.channel_position = channel_position
    self.scalar_label = scalar_label
    self.data_with_sample_dim = data_with_sample_dim
    self.concat_bands = concat_bands
    assert not self.concat_bands or len(self.non_image_modalities) == 0, (
        f"concat_bands can only be used with image modalities, "
        f"but non-image modalities are given: {self.non_image_modalities}"
    )
    assert (
        not self.concat_bands or not allow_missing_modalities
    ), "concat_bands cannot be used with allow_missing_modalities."

    if self.expand_temporal_dimension and dataset_bands is None:
        msg = "Please provide dataset_bands when expand_temporal_dimension is True"
        raise Exception(msg)

    # Load samples based on split file
    if self.split_file is not None:
        if str(self.split_file).endswith(".txt"):
            with open(self.split_file) as f:
                split = f.readlines()
            valid_files = [rf"{substring.strip()}" for substring in split]
        else:
            valid_files = list(load_table_data(self.split_file).index)

    else:
        image_files = {}
        for m, m_paths in data_root.items():
            image_files[m] = sorted(glob.glob(os.path.join(m_paths, image_grep[m])))

        def get_file_id(file_name, mod):
            glob_as_regex = '^' + ''.join('(.*?)' if ch == '*' else re.escape(ch)
                                          for ch in image_grep[mod]) + '$'
            stem = re.match(glob_as_regex, os.path.basename(file_name)).group(1)
            if allow_substring_file_names:
                # Remove file extensions
                stem = os.path.splitext(stem)[0]
            return stem

        if allow_missing_modalities:
            valid_files = list(set([get_file_id(file, mod)
                                    for mod, files in image_files.items()
                                    for file in files
                                    ]))
        else:
            valid_files = [get_file_id(file, self.modalities[0]) for file in image_files[self.modalities[0]]]

    self.samples = []
    num_modalities = len(self.modalities) + int(label_data_root is not None)

    # Check for parquet and csv files with modality data and read the file

    for m, m_path in data_root.items():
        if os.path.isfile(m_path):
            data_root[m] = load_table_data(m_path)
            # Check for some sample keys
            if not any(f in data_root[m].index for f in valid_files[:100]):
                warnings.warn(f"Sample key expected in table index (first column) for {m} (file: {m_path}). "
                              f"{valid_files[:3]+['...']} are not in index {list(data_root[m].index[:3])+['...']}.")
    if label_data_root is not None:
        if os.path.isfile(label_data_root):
            label_data_root = load_table_data(label_data_root)
            # Check for some sample keys
            if not any(f in label_data_root.index for f in valid_files[:100]):
                warnings.warn(f"Keys expected in table index (first column) for labels (file: {label_data_root}). "
                              f"The keys {valid_files[:3] + ['...']} are not in the index.")

    # Iterate over all files in split
    for file in valid_files:
        sample = {}
        # Iterate over all modalities
        for m, m_path in data_root.items():
            if isinstance(m_path, pd.DataFrame):
                # Add tabular data to sample
                sample[m] = m_path.loc[file].values
            elif allow_substring_file_names:
                # Substring match with image_grep
                m_files = sorted(glob.glob(os.path.join(m_path, file + image_grep[m])))
                if m_files:
                    sample[m] = m_files[-1]
                    if len(m_files) > 1:
                        warnings.warn(f"Found multiple matching files for sample {file} and grep {image_grep[m]}: "
                                      f"{m_files}. Selecting last one. "
                                      f"Consider changing data structure or parameters for unique selection.")
            else:
                # Exact match
                file_path = os.path.join(m_path, file)
                if os.path.exists(file_path):
                    sample[m] = file_path

        if label_data_root is not None:
            if isinstance(label_data_root, pd.DataFrame):
                # Add tabular data to sample
                sample["mask"] = label_data_root.loc[file].values
            elif allow_substring_file_names:
                # Substring match with label_grep
                l_files = sorted(glob.glob(os.path.join(label_data_root, file + label_grep)))
                if l_files:
                    sample["mask"] = l_files[-1]
            else:
                # Exact match
                file_path = os.path.join(label_data_root, file)
                if os.path.exists(file_path):
                    sample["mask"] = file_path
            if "mask" not in sample:
                # Only add sample if mask is present
                break

        if len(sample) == num_modalities or allow_missing_modalities:
            self.samples.append(sample)

    self.rgb_modality = rgb_modality or self.modalities[0]
    self.rgb_indices = rgb_indices or [0, 1, 2]

    if dataset_bands is not None:
        self.dataset_bands = {m: generate_bands_intervals(m_bands) for m, m_bands in dataset_bands.items()}
    else:
        self.dataset_bands = None
    if output_bands is not None:
        self.output_bands = {m: generate_bands_intervals(m_bands) for m, m_bands in output_bands.items()}
        for modality in self.modalities:
            if modality in self.output_bands and modality not in self.dataset_bands:
                msg = f"If output bands are provided, dataset_bands must also be provided (modality: {modality})"
                raise Exception(msg)  # noqa: PLE0101
    else:
        self.output_bands = {}

    self.filter_indices = {}
    if self.output_bands:
        for m in self.output_bands.keys():
            if m not in self.output_bands or self.output_bands[m] == self.dataset_bands[m]:
                continue
            if len(set(self.output_bands[m]) & set(self.dataset_bands[m])) != len(self.output_bands[m]):
                msg = f"Output bands must be a subset of dataset bands (Modality: {m})"
                raise Exception(msg)

            self.filter_indices[m] = [self.dataset_bands[m].index(band) for band in self.output_bands[m]]

        if not self.channel_position:
            logger.warning(
                "output_bands is defined but no channel_position is provided. "
                "Channels must be in the last dimension, otherwise provide channel_position."
            )

    # If no transform is given, apply only to transform to torch tensor
    if isinstance(transform, A.Compose):
        self.transform = MultimodalTransforms(transform,
                                              non_image_modalities=self.non_image_modalities + ['label']
                                              if scalar_label else self.non_image_modalities)
    elif transform is None:
        self.transform = MultimodalToTensor(self.modalities)
    else:
        # Modality-specific transforms
        transform = {m: transform[m] if m in transform else default_transform for m in self.modalities}
        self.transform = MultimodalTransforms(transform, shared=False)

    # Ignore rasterio warning for not geo-referenced files
    import rasterio

    warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
    warnings.filterwarnings("ignore", message="Dataset has no geotransform")

plot(sample, suptitle=None) #

Plot a sample from the dataset.

Parameters:

Name Type Description Default
sample dict[str, Tensor]

a sample returned by :meth:__getitem__

required
suptitle str | None

optional string to use as a suptitle

None

Returns:

Type Description
Figure

a matplotlib Figure with the rendered sample

.. versionadded:: 0.2

Source code in terratorch/datasets/generic_multimodal_dataset.py
def plot(self, sample: dict[str, torch.Tensor], suptitle: str | None = None) -> Figure:
    """Plot a sample from the dataset.

    Args:
        sample: a sample returned by :meth:`__getitem__`
        suptitle: optional string to use as a suptitle

    Returns:
        a matplotlib Figure with the rendered sample

    .. versionadded:: 0.2
    """
    image = sample["image"]
    if isinstance(image, dict):
        image = image[self.rgb_modality]
    if isinstance(image, torch.Tensor):
        image = image.numpy()
    image = image.take(self.rgb_indices, axis=0)
    image = np.transpose(image, (1, 2, 0))
    image = (image - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
    image = np.clip(image, 0, 1)

    if "mask" in sample:
        mask = sample["mask"]
        if isinstance(mask, torch.Tensor):
            mask = mask.numpy()
        if mask.ndim == 2:
            mask = np.expand_dims(mask, axis=-1)
        # Convert masked regions to 0.
        mask = mask * -1 + 1
    else:
        mask = None

    if "prediction" in sample:
        prediction = sample["prediction"]
        if isinstance(image, dict):
            prediction = prediction[self.rgb_modality]
        if isinstance(prediction, torch.Tensor):
            prediction = prediction.numpy()
        # Assuming reconstructed image
        prediction = prediction.take(self.rgb_indices, axis=0)
        prediction = np.transpose(prediction, (1, 2, 0))
        prediction = (prediction - image.min(axis=(0, 1))) * (1 / image.max(axis=(0, 1)))
        prediction = np.clip(prediction, 0, 1)
    else:
        prediction = None

    return self._plot_sample(
        image,
        mask=mask,
        prediction=prediction,
        suptitle=suptitle,
    )