Generic Dataclasses

Contents

Generic Dataclasses#

The generic dataclasses module provides the foundational data structures and validation logic used throughout Anomalib. These classes are designed to be flexible and type-safe, serving as the base for both PyTorch and NumPy implementations.

Core Concepts#

Type Variables#

The module uses several type variables to ensure type safety across different implementations:

  • ImageT: Type variable for image data (PyTorch Image/Video or NumPy array)

  • T: Type variable for tensor-like data (PyTorch Tensor or NumPy array)

  • MaskT: Type variable for mask data (PyTorch Mask or NumPy array)

  • PathT: Type variable for path data (string or list of strings)

Base Classes#

InputFields#

class anomalib.data.dataclasses.generic._InputFields(image, gt_label=None, gt_mask=None, mask_path=None)#

Bases: Generic[T, ImageT, MaskT, PathT], ABC

Generic dataclass that defines the standard input fields for Anomalib.

This abstract base class provides a structure for input data used in Anomalib. It defines common fields used across various anomaly detection tasks and data types.

image#

Input image or video

gt_label#

Ground truth label

gt_mask#

Ground truth segmentation mask

mask_path#

Path to mask file

Example

>>> class MyInput(_InputFields[int, Image, Mask, str]):
...     def validate_image(self, image):
...         return image
...     # Implement other validation methods
...
>>> input_data = MyInput(
...     image=torch.rand(3,224,224),
...     gt_label=1,
...     gt_mask=None,
...     mask_path=None
... )
abstract static validate_gt_label(gt_label)#

Validate the ground truth label.

Parameters:

gt_label (TypeVar(T, Tensor, ndarray)) – Ground truth label to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated label or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_gt_mask(gt_mask)#

Validate the ground truth mask.

Parameters:

gt_mask (TypeVar(MaskT, Mask, ndarray)) – Ground truth mask to validate

Return type:

Optional[TypeVar(MaskT, Mask, ndarray)]

Returns:

Validated mask or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_image(image)#

Validate the image.

Parameters:

image (TypeVar(ImageT, Image, Video, ndarray)) – Input image to validate

Return type:

TypeVar(ImageT, Image, Video, ndarray)

Returns:

Validated image

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_mask_path(mask_path)#

Validate the mask path.

Parameters:

mask_path (TypeVar(PathT, list[str], str)) – Path to mask file to validate

Return type:

Optional[TypeVar(PathT, list[str], str)]

Returns:

Validated path or None

Raises:

NotImplementedError – Must be implemented by subclass

ImageInputFields#

class anomalib.data.dataclasses.generic._ImageInputFields(image_path=None)#

Bases: Generic[PathT], ABC

Generic dataclass for image-specific input fields in Anomalib.

This class extends standard input fields with an image_path attribute for image-based anomaly detection tasks.

image_path#

Path to input image file

Example

>>> class MyImageInput(_ImageInputFields[str]):
...     def validate_image_path(self, path):
...         return path
...
>>> input_data = MyImageInput(image_path="path/to/image.jpg")
abstract static validate_image_path(image_path)#

Validate the image path.

Parameters:

image_path (TypeVar(PathT, list[str], str)) – Path to validate

Return type:

Optional[TypeVar(PathT, list[str], str)]

Returns:

Validated path or None

Raises:

NotImplementedError – Must be implemented by subclass

VideoInputFields#

class anomalib.data.dataclasses.generic._VideoInputFields(original_image=None, video_path=None, target_frame=None, frames=None, last_frame=None)#

Bases: Generic[T, ImageT, MaskT, PathT], ABC

Generic dataclass that defines the video input fields for Anomalib.

This class extends standard input fields with attributes specific to video-based anomaly detection tasks.

original_image#

Original frame from video

video_path#

Path to input video file

target_frame#

Frame number to process

frames#

Sequence of video frames

last_frame#

Last frame in sequence

Example

>>> class MyVideoInput(_VideoInputFields[int, Image, Mask, str]):
...     def validate_original_image(self, image):
...         return image
...     # Implement other validation methods
...
>>> input_data = MyVideoInput(
...     original_image=torch.rand(3,224,224),
...     video_path="video.mp4",
...     target_frame=10,
...     frames=None,
...     last_frame=None
... )
abstract static validate_frames(frames)#

Validate the frames.

Parameters:

frames (TypeVar(T, Tensor, ndarray)) – Frame sequence to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated frames or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_last_frame(last_frame)#

Validate the last frame.

Parameters:

last_frame (TypeVar(T, Tensor, ndarray)) – Frame to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated frame or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_original_image(original_image)#

Validate the original image.

Parameters:

original_image (TypeVar(ImageT, Image, Video, ndarray)) – Image to validate

Return type:

Optional[TypeVar(ImageT, Image, Video, ndarray)]

Returns:

Validated image or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_target_frame(target_frame)#

Validate the target frame.

Parameters:

target_frame (TypeVar(T, Tensor, ndarray)) – Frame number to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated frame number or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_video_path(video_path)#

Validate the video path.

Parameters:

video_path (TypeVar(PathT, list[str], str)) – Path to validate

Return type:

Optional[TypeVar(PathT, list[str], str)]

Returns:

Validated path or None

Raises:

NotImplementedError – Must be implemented by subclass

DepthInputFields#

class anomalib.data.dataclasses.generic._DepthInputFields(image_path=None, depth_map=None, depth_path=None)#

Bases: Generic[T, PathT], _ImageInputFields[PathT], ABC

Generic dataclass that defines the depth input fields for Anomalib.

This class extends standard input fields with depth-specific attributes for depth-based anomaly detection tasks.

depth_map#

Depth map image

depth_path#

Path to depth map file

Example

>>> class MyDepthInput(_DepthInputFields[torch.Tensor, str]):
...     def validate_depth_map(self, depth):
...         return depth
...     def validate_depth_path(self, path):
...         return path
...     # Implement other validation methods
...
>>> input_data = MyDepthInput(
...     image_path="rgb.jpg",
...     depth_map=torch.rand(224,224),
...     depth_path="depth.png"
... )
abstract static validate_depth_map(depth_map)#

Validate the depth map.

Parameters:

depth_map (TypeVar(ImageT, Image, Video, ndarray)) – Depth map to validate

Return type:

Optional[TypeVar(ImageT, Image, Video, ndarray)]

Returns:

Validated depth map or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_depth_path(depth_path)#

Validate the depth path.

Parameters:

depth_path (TypeVar(PathT, list[str], str)) – Path to validate

Return type:

Optional[TypeVar(PathT, list[str], str)]

Returns:

Validated path or None

Raises:

NotImplementedError – Must be implemented by subclass

OutputFields#

class anomalib.data.dataclasses.generic._OutputFields(anomaly_map=None, pred_score=None, pred_mask=None, pred_label=None, explanation=None)#

Bases: Generic[T, MaskT, PathT], ABC

Generic dataclass that defines the standard output fields for Anomalib.

This class defines the standard output fields used in Anomalib, including anomaly maps, predicted scores, masks, and labels.

anomaly_map#

Predicted anomaly heatmap

pred_score#

Predicted anomaly score

pred_mask#

Predicted segmentation mask

pred_label#

Predicted label

explanation#

Path to explanation visualization

Example

>>> class MyOutput(_OutputFields[float, Mask, str]):
...     def validate_anomaly_map(self, amap):
...         return amap
...     # Implement other validation methods
...
>>> output = MyOutput(
...     anomaly_map=torch.rand(224,224),
...     pred_score=0.7,
...     pred_mask=None,
...     pred_label=1,
...     explanation=None
... )
abstract static validate_anomaly_map(anomaly_map)#

Validate the anomaly map.

Parameters:

anomaly_map (TypeVar(MaskT, Mask, ndarray)) – Anomaly map to validate

Return type:

Optional[TypeVar(MaskT, Mask, ndarray)]

Returns:

Validated anomaly map or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_explanation(explanation)#

Validate the explanation.

Parameters:

explanation (TypeVar(PathT, list[str], str)) – Explanation to validate

Return type:

Optional[TypeVar(PathT, list[str], str)]

Returns:

Validated explanation or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_pred_label(pred_label)#

Validate the predicted label.

Parameters:

pred_label (TypeVar(T, Tensor, ndarray)) – Label to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated label or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_pred_mask(pred_mask)#

Validate the predicted mask.

Parameters:

pred_mask (TypeVar(MaskT, Mask, ndarray)) – Mask to validate

Return type:

Optional[TypeVar(MaskT, Mask, ndarray)]

Returns:

Validated mask or None

Raises:

NotImplementedError – Must be implemented by subclass

abstract static validate_pred_score(pred_score)#

Validate the predicted score.

Parameters:

pred_score (TypeVar(T, Tensor, ndarray)) – Score to validate

Return type:

Optional[TypeVar(T, Tensor, ndarray)]

Returns:

Validated score or None

Raises:

NotImplementedError – Must be implemented by subclass

Mixins#

UpdateMixin#

class anomalib.data.dataclasses.generic.UpdateMixin#

Bases: object

Mixin class for dataclasses that allows for in-place replacement of attrs.

This mixin provides methods for updating dataclass instances in place or by creating a new instance.

Example

>>> @dataclass
... class MyItem(UpdateMixin):
...     field1: int
...     field2: str
...
>>> item = MyItem(field1=1, field2="a")
>>> item.update(field1=2)  # In-place update
>>> item.field1
2
>>> new_item = item.update(in_place=False, field2="b")
>>> new_item.field2
'b'
update(in_place=True, **changes)#

Replace fields in place and call __post_init__ to reinitialize.

Parameters:
  • in_place (bool) – Whether to modify in place or return new instance

  • **changes – Field names and new values to update

Return type:

Any

Returns:

Updated instance (self if in_place=True, new instance otherwise)

Raises:

TypeError – If instance is not a dataclass

BatchIterateMixin#

class anomalib.data.dataclasses.generic.BatchIterateMixin#

Bases: Generic[ItemT]

Mixin class for iterating over batches of items in Anomalib datasets.

This class provides functionality to iterate over individual items within a batch and convert batches to lists of items.

item_class#

Class to use for individual items in the batch

Example

>>> @dataclass
... class MyBatch(BatchIterateMixin):
...     item_class = MyItem
...     data: torch.Tensor
...
>>> batch = MyBatch(data=torch.rand(32,3,224,224))
>>> for item in batch:
...     process_item(item)
>>> items = batch.items  # Convert to list of items
property batch_size: int#

Get the batch size.

Returns:

Number of items in batch

Raises:

AttributeError – If image attribute is not set

classmethod collate(items)#

Convert a list of DatasetItem objects to a Batch object.

Parameters:

items (list[TypeVar(ItemT, bound= _GenericItem)]) – List of items to collate into a batch

Return type:

BatchIterateMixin

Returns:

New batch containing the items

property items: list[ItemT]#

Convert the batch to a list of DatasetItem objects.

Returns:

List of individual items from the batch

Generic Classes#

GenericItem#

class anomalib.data.dataclasses.generic._GenericItem(image, gt_label=None, gt_mask=None, mask_path=None, anomaly_map=None, pred_score=None, pred_mask=None, pred_label=None, explanation=None)#

Bases: UpdateMixin, Generic[T, ImageT, MaskT, PathT], _OutputFields[T, MaskT, PathT], _InputFields[T, ImageT, MaskT, PathT]

Generic dataclass for a single item in Anomalib datasets.

This class combines input and output fields for anomaly detection tasks. It inherits from _InputFields for standard input data and _OutputFields for prediction results.

Example

>>> class MyItem(_GenericItem[int, Image, Mask, str]):
...     def validate_image(self, image):
...         return image
...     # Implement other validation methods
...
>>> item = MyItem(
...     image=torch.rand(3,224,224),
...     gt_label=0,
...     pred_score=0.3,
...     anomaly_map=torch.rand(224,224)
... )
>>> item.update(pred_score=0.8)

GenericBatch#

class anomalib.data.dataclasses.generic._GenericBatch(image, gt_label=None, gt_mask=None, mask_path=None, anomaly_map=None, pred_score=None, pred_mask=None, pred_label=None, explanation=None)#

Bases: UpdateMixin, Generic[T, ImageT, MaskT, PathT], _OutputFields[T, MaskT, PathT], _InputFields[T, ImageT, MaskT, PathT]

Generic dataclass for a batch of items in Anomalib datasets.

This class represents a batch of data items, combining both input and output fields for anomaly detection tasks.

Example

>>> class MyBatch(_GenericBatch[int, Image, Mask, str]):
...     def validate_image(self, image):
...         return image
...     # Implement other validation methods
...
>>> batch = MyBatch(
...     image=torch.rand(32,3,224,224),
...     gt_label=torch.zeros(32),
...     pred_score=torch.rand(32)
... )

Field Validation#

FieldDescriptor#

class anomalib.data.dataclasses.generic.FieldDescriptor(validator_name=None, default=None)#

Bases: Generic[Value]

Descriptor for Anomalib’s dataclass fields.

Using a descriptor ensures that the values of dataclass fields can be validated before being set. This allows validation of the input data not only when it is first set, but also when it is updated.

Parameters:
  • validator_name (str | None) – Name of the validator method to call when setting value. Defaults to None.

  • default (Optional[TypeVar(Value)]) – Default value for the field. Defaults to None.

Example

>>> class MyClass:
...     field = FieldDescriptor(validator_name="validate_field")
...     def validate_field(self, value):
...         return value
...
>>> obj = MyClass()
>>> obj.field = 42
>>> obj.field
42
get_types(owner)#

Get the types of the descriptor.

Parameters:

owner (type[TypeVar(Instance)]) – Class that owns the descriptor

Return type:

tuple[type, ...]

Returns:

Tuple of valid types for this field

Raises:

TypeError – If types cannot be determined

is_optional(owner)#

Check if the descriptor is optional.

Parameters:

owner (type[TypeVar(Instance)]) – Class that owns the descriptor

Return type:

bool

Returns:

True if field can be None, False otherwise

See Also#