Overview
Theutils 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
Directory where segmentation visualization images will be saved. Created automatically if it doesn’t exist.
List of paths to the original input images.
List of predicted anomaly segmentation maps. Each array should be 2D (H, W) representing anomaly heatmaps.
Optional list of image-level anomaly scores corresponding to each image.
Optional list of paths to ground truth mask images for comparison.
Optional function to transform images before visualization (e.g., denormalization).
Optional function to transform masks before visualization.
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
Root directory for all results.
Project-level subdirectory name.
Experiment group folder name.
Folder creation mode:
"iterate": Appends counter (_0, _1, _2…) if folder exists"overwrite": Uses existing folder or creates new one
Returns
Full path to the created storage folder.
Example
set_torch_device
Configures and returns the appropriate PyTorch device based on GPU availability.Parameters
List of GPU device IDs to use. If empty list, CPU is selected.
Returns
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
Random seed value to set across all libraries.
If True, fixes PyTorch CPU random seed.
If True, fixes PyTorch CUDA random seeds and enables deterministic mode.
Behavior
Always sets:random.seed(seed)- Python standard librarynp.random.seed(seed)- NumPy
with_torch=True, additionally sets:
torch.manual_seed(seed)- PyTorch CPU
with_cuda=True, additionally sets:
torch.cuda.manual_seed(seed)- Single GPUtorch.cuda.manual_seed_all(seed)- All GPUstorch.backends.cudnn.deterministic = True- Deterministic cuDNN
Example
compute_and_store_final_results
Computes mean metrics across multiple datasets and saves results as a CSV file.Parameters
Directory where the results CSV file will be saved.
List of result lists, where each inner list contains metrics for one dataset/class. Each inner list should contain values corresponding to
column_names.Optional list of names for each row (e.g., dataset names or class names). Must match length of
results.Names of the metric columns. Default:
- “Instance AUROC”
- “Full Pixel AUROC”
- “Full PRO”
- “Anomaly Pixel AUROC”
- “Anomaly PRO”
Returns
Dictionary with keys
"mean_{column_name}" containing the mean value for each metric across all datasets.Output File
Createsresults.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
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.