Dataset#

class maite.protocols.object_detection.Dataset(*args, **kwargs)[source]#

A dataset protocol for object detection AI problem providing datum-level data access.

Implementers must provide index lookup (via __getitem__(ind: int) method) and support len (via __len__() method). Data elements looked up this way correspond to individual examples (as opposed to batches).

Indexing into or iterating over the an object detection dataset returns a tuple of types Image, ObjectDetectionTarget, and DatumMetadata. These correspond to the model input type, model target type, and datum-level metadata, respectively. The model input (Image) is expected to follow (C, H, W) shape semantics.

Attributes:
metadataDatasetMetadata

A typed dictionary containing at least an ‘id’ field of type str

Methods

__getitem__(ind: int) -> tuple[Image, ObjectDetectionTarget, DatumMetadata]

Provide mapping-style access to dataset elements. Returned tuple elements correspond to model input type, model target type, and datum-specific metadata, respectively.

__len__() -> int

Return the number of data elements in the dataset.

Examples

We generate a dummy set of data and use it with a class that implements the lightweight dataset protocol:

>>> import numpy as np
>>> from dataclasses import dataclass
>>> from maite.protocols import DatumMetadata, DatasetMetadata, object_detection as od
>>> from typing import Generator

We will generate 12 images with random data, each having 3 color channels and a height and width of 10 pixels.

>>> N_DATUM = 12
>>> C, H, W = 3, 10, 10
>>> images: list[np.ndarray] = list(np.random.rand(N_DATUM, C, H, W))

Each image may have zero, one, or two detections, which will be chosen at random. Each detection will have a randomly-drawn bounding box (with a minimum and maximum size in each dimension) and a label chosen randomly from 2 classes. The bounding box coordinates and labels are the “annotations” for the image.

>>> MAX_DETECTIONS = 2
>>> MIN_BOX_SIZE, MAX_BOX_SIZE = 2, 4
>>> N_CLASSES = 2
>>> def generate_random_annotations() -> Generator[np.ndarray]:
...     for _ in range(N_DATUM):
...         n_detections = np.random.choice(MAX_DETECTIONS + 1)
...         box_sizes = np.random.randint(MIN_BOX_SIZE, MAX_BOX_SIZE, (n_detections, 2))
...         box_tl_coords = np.random.randint(0, np.array([W, H]) - box_sizes)
...         box_br_coords = box_tl_coords + box_sizes
...         labels = np.random.choice(N_CLASSES, (n_detections, 1))
...         yield np.hstack([box_tl_coords, box_br_coords, labels])
>>> annotations: list[np.ndarray] = list(generate_random_annotations())

Each image has a randomly-chosen hour of day that it was taken. The datum-specific metadata class is extended to include the hour of day (along with the unique id).

>>> hours_of_day: list[int] = list(np.random.choice(24, N_DATUM))
>>> class MyDatumMetadata(DatumMetadata):
...     hour_of_day: int

An object detection target class defines the bounding boxes, labels, and scores for each detection in an image.

>>> @dataclass
... class MyObjectDetectionTarget:
...     boxes: np.ndarray
...     labels: np.ndarray
...     scores: np.ndarray

Now we can construct a compliant dataset with a simple wrapper that fetches individual data points, where a data point is a single image, ground truth detection(s), and metadata.

>>> class ImageDataset:
...     # Set up required dataset-level metadata
...     metadata: DatasetMetadata = {
...         "id": "Dummy Dataset",
...         "index2label": {i: f"class_name_{i}" for i in range(N_CLASSES)},
...     }
...
...     def __init__(self, images: list[np.ndarray], annotations: list[np.ndarray], hours_of_day: list[int]):
...         self.images = images
...         self.annotations = annotations
...         self.hours_of_day = hours_of_day
...
...     def __len__(self) -> int:
...         return len(self.images)
...
...     def __getitem__(self, index: int) -> tuple[np.ndarray, MyObjectDetectionTarget, MyDatumMetadata]:
...         if index < 0 or index >= len(self):
...             raise IndexError(f"Index {index} is out of range for the dataset, which has length {len(self)}.")
...         image, annotations, hour_of_day = self.images[index], self.annotations[index], self.hours_of_day[index]
...         # Structure ground truth target
...         boxes, labels = np.hsplit(annotations, [-1])
...         scores = np.ones_like(labels)
...         od_target = MyObjectDetectionTarget(boxes, labels, scores)
...         # Structure datum-level metadata
...         datum_metadata: MyDatumMetadata = {
...             "id": str(index),
...             "hour_of_day": hour_of_day,
...         }
...         return image, od_target, datum_metadata

We can instantiate this class and type hint it as an object_detection.Dataset. By using type hinting, we permit a static typechecker to verify protocol compliance.

>>> maite_od_dataset: od.Dataset = ImageDataset(images, annotations, hours_of_day)
>>> print(len(maite_od_dataset))
12

Note that when writing a Dataset implementer, return types may be narrower than the return types promised by the protocol (np.ndarray is a subtype of ArrayLike), but the argument types must be at least as general as the argument types promised by the protocol.