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.
- 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:
- 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.
ImageInputFields#
- class anomalib.data.dataclasses.generic._ImageInputFields(image_path=None)#
-
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")
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.
- abstract static validate_last_frame(last_frame)#
Validate the last frame.
- abstract static validate_original_image(original_image)#
Validate the original image.
- Parameters:
original_image (
TypeVar
(ImageT
,Image
,Video
,ndarray
)) – Image to validate- Return type:
- Returns:
Validated image or None
- Raises:
NotImplementedError – Must be implemented by subclass
- abstract static validate_target_frame(target_frame)#
Validate the target frame.
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:
- Returns:
Validated depth map 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:
- Returns:
Validated anomaly map or None
- Raises:
NotImplementedError – Must be implemented by subclass
- abstract static validate_explanation(explanation)#
Validate the explanation.
- abstract static validate_pred_label(pred_label)#
Validate the predicted label.
- abstract static validate_pred_mask(pred_mask)#
Validate the predicted mask.
- Parameters:
pred_mask (
TypeVar
(MaskT
,Mask
,ndarray
)) – Mask to validate- Return type:
- Returns:
Validated mask 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.
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
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:
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.