Skip to main content

Overview

The utils module provides essential utility functions for PatchCore, including visualization of segmentation results, storage management, device configuration, random seed fixing, and results computation.

Functions

plot_segmentation_images

Generates and saves visualization images comparing original images, ground truth masks, and predicted anomaly segmentations.

Parameters

str
required
Directory where segmentation visualization images will be saved. Created automatically if it doesn’t exist.
List[str]
required
List of paths to the original input images.
List[np.ndarray]
required
List of predicted anomaly segmentation maps. Each array should be 2D (H, W) representing anomaly heatmaps.
List[float] | None
default:"None"
Optional list of image-level anomaly scores corresponding to each image.
List[str] | None
default:"None"
Optional list of paths to ground truth mask images for comparison.
callable
default:"lambda x: x"
Optional function to transform images before visualization (e.g., denormalization).
callable
default:"lambda x: x"
Optional function to transform masks before visualization.
int
default:"4"
Number of path components to use from image_path for generating save filenames.

Behavior

  • Creates a 2-column plot (3-column if masks provided) showing:
    • Column 1: Original image
    • Column 2: Ground truth mask (if provided)
    • Column 3: Predicted segmentation heatmap
  • Saves each visualization as a PNG file
  • Shows progress bar during generation

create_storage_folder

Creates a hierarchical folder structure for organizing experiment results.

Parameters

str
required
Root directory for all results.
str
required
Project-level subdirectory name.
str
required
Experiment group folder name.
str
default:"iterate"
Folder creation mode:
  • "iterate": Appends counter (_0, _1, _2…) if folder exists
  • "overwrite": Uses existing folder or creates new one

Returns

str
Full path to the created storage folder.

Example


set_torch_device

Configures and returns the appropriate PyTorch device based on GPU availability.

Parameters

List[int]
required
List of GPU device IDs to use. If empty list, CPU is selected.

Returns

torch.device
PyTorch device object configured for the specified GPU or CPU.

Example


fix_seeds

Sets random seeds for reproducible experiments across NumPy, Python random, and PyTorch.

Parameters

int
required
Random seed value to set across all libraries.
bool
default:"True"
If True, fixes PyTorch CPU random seed.
bool
default:"True"
If True, fixes PyTorch CUDA random seeds and enables deterministic mode.

Behavior

Always sets:
  • random.seed(seed) - Python standard library
  • np.random.seed(seed) - NumPy
If with_torch=True, additionally sets:
  • torch.manual_seed(seed) - PyTorch CPU
If with_cuda=True, additionally sets:
  • torch.cuda.manual_seed(seed) - Single GPU
  • torch.cuda.manual_seed_all(seed) - All GPUs
  • torch.backends.cudnn.deterministic = True - Deterministic cuDNN
Setting with_cuda=True enables deterministic mode which may reduce performance. Only use for reproducibility testing.

Example


compute_and_store_final_results

Computes mean metrics across multiple datasets and saves results as a CSV file.

Parameters

str
required
Directory where the results CSV file will be saved.
List[List[float]]
required
List of result lists, where each inner list contains metrics for one dataset/class. Each inner list should contain values corresponding to column_names.
List[str] | None
default:"None"
Optional list of names for each row (e.g., dataset names or class names). Must match length of results.
List[str]
default:"[...]"
Names of the metric columns. Default:
  • “Instance AUROC”
  • “Full Pixel AUROC”
  • “Full PRO”
  • “Anomaly Pixel AUROC”
  • “Anomaly PRO”

Returns

dict
Dictionary with keys "mean_{column_name}" containing the mean value for each metric across all datasets.

Output File

Creates results.csv in the specified path with:
  • Header row with column names
  • One row per dataset with metric values
  • Final row with mean values across all datasets

Example

Generated CSV (results.csv):

Complete Workflow Example


Logging

The utils module uses Python’s standard logging module:

Notes

Image Transforms: The plot_segmentation_images function expects transforms that can handle both PIL images and tensors. Ensure your transforms are compatible.
Save Depth: The save_depth parameter controls how many directory levels from the image path are used in the filename. Adjust based on your directory structure to avoid name collisions.
Deterministic Performance: Using fix_seeds with with_cuda=True enables cuDNN deterministic mode, which may reduce training/inference speed by 10-20%. Use only when reproducibility is critical.