Skip to content

Adding a new output collector

HistoKit supports custom output collectors through a common OutputCollector interface. Collectors receive intermediate or final pipeline outputs and are responsible for processing, visualizing, or saving the generated data.

1. Inherit from the base class

All output collectors must inherit from the OutputCollector base class and implement the emit() method.

Method Description
__init__() Initializes the output directory and collector-specific parameters.
emit(output) Processes a pipeline output and optionally saves the generated data.

The emit() method receives a PipelineOutput object containing the generated data and associated metadata.

Pipeline output structure

Field Description
name Name identifying the generated output.
kind Output data category, represented by OutputKind.
data Generated data, such as an image, mask, or histogram.
metadata Additional information associated with the output.

Collectors can use these fields to determine whether a given output should be processed.

2. Implement the collector

Define a new collector class with the required configuration parameters and implement the emit() method.

The following example implements a collector that calculates binary mask statistics and saves them as a JSON file:

import json
from pathlib import Path

import numpy as np

from .base import OutputCollector, OutputKind, PipelineOutput


class MaskStatisticsCollector(OutputCollector):
    def __init__(
        self,
        out_dir,
        indent: int = 4,
    ):
        self.out_dir = Path(out_dir)
        self.indent = indent

    def emit(self, output: PipelineOutput) -> None:
        if output.kind != OutputKind.MASK:
            return

        basename = output.metadata.get("basename", "mask")
        step = output.metadata.get("step", "masks")

        save_dir = self.out_dir / "statistics" / step
        save_dir.mkdir(parents=True, exist_ok=True)

        mask = np.asarray(output.data)

        total_pixels = int(mask.size)
        foreground_pixels = int(np.count_nonzero(mask))

        statistics = {
            "total_pixels": total_pixels,
            "foreground_pixels": foreground_pixels,
            "background_pixels": total_pixels - foreground_pixels,
            "foreground_ratio": (
                foreground_pixels / total_pixels
                if total_pixels > 0
                else 0.0
            ),
        }

        with (save_dir / f"{basename}.json").open(
            "w", encoding="utf-8"
        ) as file:
            json.dump(statistics, file, indent=self.indent)
Parameter Default Description
out_dir Required Base directory used for saving collector outputs.
indent 4 Indentation level used for JSON serialization.

The collector processes mask outputs, calculates foreground and background statistics, and saves the results in an output directory.

3. Filter pipeline outputs

Collectors should process only the outputs relevant to their functionality. Unsupported outputs should be ignored by returning early from the emit() method.

Filtering by output kind

Use OutputKind to select outputs belonging to a specific data category:

def emit(self, output: PipelineOutput) -> None:
    if output.kind != OutputKind.MASK:
        return

    # Process the mask.

Multiple output kinds can also be supported:

if output.kind not in {OutputKind.IMAGE, OutputKind.MASK}:
    return

Filtering by output name

Use the output name when the collector is designed to process a specific pipeline output:

def emit(self, output: PipelineOutput) -> None:
    if output.name != "thumbnail":
        return

    # Process the thumbnail.

Filtering by name is particularly useful for specialized collectors, such as segmentation overlays, thumbnails, and histograms.

Both filtering mechanisms can be combined when necessary.

4. Access output metadata

The metadata dictionary provides additional information required by the collector.

Example metadata fields used by available collectors:

Field Description
basename Base filename used for saving outputs.
step Pipeline stage associated with the output.
image Reference image used for generating overlays.
colors Mapping of class identifiers to visualization colors.

Use metadata.get() for optional fields and provide appropriate default values:

basename = output.metadata.get("basename", "output")
step = output.metadata.get("step", "statistics")

For required metadata fields, use direct dictionary access:

image = np.asarray(output.metadata["image"])

5. Register the collector

To make the collector available through algorithm configuration, import the new collector class and add it to the algorithm's collector_registry.

collector_registry = {
    # Existing collectors...
    "mask_statistics": MaskStatisticsCollector,
}

6. Configure the collector

Once registered, the collector can be enabled through the algorithm configuration.

Use the collector name to initialize it with default parameters:

collectors:
  - mask_statistics

To override collector-specific parameters, use the dictionary configuration format:

collectors:
  - name: mask_statistics
    params:
      indent: 2

All identifiers must correspond to entries in the algorithm's collector_registry.

The build_output_collector() method initializes the configured collectors and combines them into a CompositeOutputCollector.

7. Emit compatible pipeline outputs

Ensure that the segmenter emits outputs compatible with the new collector.

For example, the MaskStatisticsCollector can process masks emitted through the inherited _collect() method:

self._collect(
    name="tissue_mask",
    step="segmentation",
    kind="mask",
    data=mask,
    basename="slide_001",
)

The collector receives the corresponding PipelineOutput, checks its kind, calculates mask statistics, and saves the result.

If the output directory is ./outputs, the generated file structure is:

outputs/
└── statistics/
    └── segmentation/
        └── slide_001.json

An example of the generated JSON file:

{
    "total_pixels": 10000,
    "foreground_pixels": 7500,
    "background_pixels": 2500,
    "foreground_ratio": 0.75
}

Built-in output collectors

HistoKit provides several built-in collectors that can serve as references when implementing new collectors.

Collector Output filter Description
ImageOutputCollector OutputKind.IMAGE, OutputKind.MASK Saves images and masks as PNG files.
ThumbnailCollector thumbnail Saves slide thumbnails.
MaskCollector OutputKind.MASK Saves segmentation masks as PNG files.
SegmentationOverlayCollector tissue_overlay Draws tissue segmentation contours on a reference image.
ArtifactOverlayCollector artifact_overlay Generates color-coded artifact maps and overlays.
HistogramCollector histograms Generates RGB histogram visualizations with threshold markers.