HistoQC 2.0

repository·master·Indexed 43 days ago

https://github.com/choosehappy/histoqc

An open-source digital pathology quality control tool and modular pipeline for histological image quality control. It provides automated assessment of slide quality and allows developers to extend functionality via custom Python modules that interact with image metadata and masks.

Tokens
19.4K
Snippets
67
Records
82
Agent score
55%

What's inside HistoQC

  1. Understand the HistoQC pipeline and mask refinement model

    master

    HistoQC operates as a sequential pipeline of modules applied to an image. The core mechanism is the refinement of a pixel mask called img_mask_use.

    1. Initial State: When an image is loaded, it is assigned a "True mask" (img_mask_use) where every pixel is considered artifact-free and "useful" for analysis.
    2. Sequential Refinement: As modules run, they update img_mask_use to exclude pixels that fail certain criteria (e.g., background, artifacts, or low-intensity areas).
    3. Module Interaction: Many modules include a limit_to_mask option. When enabled, the module only performs operations on pixels currently marked as true in the img_mask_use mask.

    Important: Because modules refine the same mask, the order of modules in your pipeline is critical. A module that identifies and masks out background (like LightDarkModule.getIntensityThresholdPercent:tissue) should be placed before modules that calculate statistics (like HistogramModule.getHistogram) to ensure the statistics are only calculated on valid tissue areas.

  2. Apply a threshold to classification probability maps

    master
    After a classification model is trained, it generates a probability likelihood for each pixel belonging to the trained positive class. Because raw probability values are not suitable for downstream analysis, you must use the tresh parameter to apply a threshold to the probability map. This converts the probability map into a final binary value mask.
  3. Install HistoQC using Docker

    master

    Docker is the recommended installation method for HistoQC to ensure portability and reproducible behavior. This method avoids Python environment management issues and works on Windows, MacOS, and Linux.

    To run HistoQC, pull the official image from Docker Hub and run it with the following command structure. You must map a local directory to the /data directory inside the container to access your files and specify a local port to map to the container's port 5000.

    docker run -v <local-path>:/data --name <container-name> -p <local-port>:5000 -it histotools/histoqc:master /bin/bash
    
    # Example:
    docker run -v /local/datadir:/data --name my_container -p 5000:5000 -it histotools/histoqc:master /bin/bash
  4. Augment classifier features using skimage filters

    master

    To improve classifier robustness, you can augment the original RGB space by computing additional pixel-features. HistoQC uses features implemented in skimage.filters.

    Available features include:

    • frangi
    • laplace
    • rgb
    • lbp (commented out in default)
    • gabor (commented out in default)
    • median (commented out in default)
    • gaussian (commented out in default)

    Configuring Feature Parameters: You can set specific parameters for a filter by using the feature name as a prefix to the parameter name. For example, to set the black_ridges parameter of the frangi filter to True, use frangi_black_ridges: True.

    features:  frangi
               laplace
               rgb
               #lbp
               #gabor
               #median
               #gaussian
    
    # Example of setting a specific filter parameter:
    frangi_black_ridges: True
  5. Configure classification type modules with exemplar images

    master

    Classification modules in HistoQC use a model-based approach rather than simple statistics. To set this up, you must provide a set of exemplar images and their corresponding binary masks using the examples parameter.

    Each line in the examples parameter must specify one exemplar set using the format: path/to/original_image.png:path/to/binary_mask.png.

    Requirements for exemplars:

    • Mask Format: The mask must be a binary image containing only values {0, 1}. A value of 1 identifies pixels for the positive class, and 0 identifies pixels for the negative class.
    • Image Size: For optimal performance, exemplar images should be of the same magnification specified by the image_work_size parameter.
    • Pathing: You can use either relative or absolute paths.
    examples: ./pen/1k_version/pen_green.png:./pen/1k_version/pen_green_mask.png
              #./pen/1k_version/pen_red.png:./pen/1k_version/pen_red_mask.png
  6. Configure the HistoQC pipeline order

    master

    The HistoQC pipeline is defined using a configuration file following Python's configparser syntax. The core of the pipeline is the [pipeline] section, which defines the sequence of modules to be executed on each image.

    Module Naming and Reusability

    You can use the same module multiple times in a single pipeline by assigning it a unique instance name using the syntax ModuleName.method:instance_name.

    When you create an instance (e.g., LightDarkModule.getIntensityThresholdPercent:tissue), you must define a corresponding section in the config file named exactly after that instance (e.g., [LightDarkModule.getIntensityThresholdPercent:tissue]). This section must contain a name: parameter, which determines the output name of the image and the column name in the resulting TSV file.

    Example Pipeline Configuration

    [pipeline]
    steps= BasicModule.getBasicStats
        BasicModule.getMag
        ClassificationModule.byExampleWithFeatures:pen_markings
        ClassificationModule.byExampleWithFeatures:coverslip_edge
        LightDarkModule.getIntensityThresholdPercent:tissue
        LightDarkModule.getIntensityThresholdPercent:darktissue
        MorphologyModule.removeSmallObjects
        MorphologyModule.fillSmallHoles
        BlurDetectionModule.identifyBlurryRegions
        BasicModule.finalProcessingSpur
        BasicModule.finalProcessingArea
        HistogramModule.compareToTemplates
        HistogramModule.getHistogram
        BrightContrastModule.getContrast
        BrightContrastModule.getBrightness
        DeconvolutionModule.seperateStains
        SaveModule.saveFinalMask
        SaveModule.saveThumbnail
        BasicModule.finalComputations
  7. Suggested HistoQC Workflow

    master

    The recommended workflow for processing histology images with HistoQC involves a two-step approach to ensure data homogeneity and prevent computational errors (like out-of-memory issues).

    Step 1: Discovery and Cohort Splitting

    Run HistoQC using a minimal pipeline (e.g., config_first.ini). This step is used to:

    • Identify images scanned at different magnifications (e.g., 20x vs 40x).
    • Perform basic tissue detection (white threshold).
    • Compute histograms and differences to target templates.

    Goal: Split your dataset into sub-cohorts that share the same magnification, the same number of internal storage levels, and similar appearance properties (lightness, stain intensity, etc.).

    Using the Web UI:

    • Use the parallel coordinates graph to create filters by clicking and dragging on axes.
    • Use "Save Filtered" to save a specific subset of images based on your filters.
    • Use "Delete" (after multi-selecting) to remove unsuitable images from the table.
    • Click "Save" to generate an output file containing only the selected subset.

    Step 2: Full Pipeline Execution

    Once sub-cohorts are established, rerun the pipeline using an expanded set of models (e.g., using config.ini designed for 40x H&E images). This step allows you to:

    • Identify images with artifacts unsuitable for computation.
    • Verify if suggested masks are appropriate for downstream tasks by using the "compare" dropdown and selecting _fuse.png to view the original image alongside fused images.
  8. Create and register a new HistoQC module

    master

    To extend HistoQC, create a new Python file where the filename represents the module class (e.g., HistogramModule.py). Inside this file, define functions that perform specific tasks.

    To integrate your module into the HistoQC pipeline:

    1. Add the function to the [pipeline] section in the configuration file using the format filename.function (omitting the .py extension). For example, if your file is HistogramModule.py and your function is compareTemplates, add HistogramModule.compareTemplates to the steps list.
    2. To provide custom parameters for your function, add a section at the bottom of the configuration file named [filename.function].
    # Example configuration entry
    [pipeline]
    steps = [
        "HistogramModule.compareTemplates",
        ...
    ]
    
    [HistogramModule.compareTemplates]
    threshold = 0.7
  9. Save output images from a module

    master

    To save a new mask or output image, use the s["outdir"], s["filename"], and os.sep to construct the path. This ensures images are saved in the correct location for the pipeline.

    Naming Convention: Append an underscore followed by a descriptive name and the extension (e.g., _MyMask.png).

    Registering with the UI: To make your new image type visible in the HistoQC front-end, you must manually add the file extension suffix to the DEFAULT_IMAGE_EXTENSIONS list in global_config.js.

    import os
    from skimage import io
    import numpy as np
    
    # Example: saving a binary mask
    # Convert 0/1 mask to 0/255 for visibility
    io.imsave(s["outdir"] + os.sep + s["filename"] + "_BubbleBounds.png", mask.astype(np.uint8) * 255)
  10. Specify file paths in the HistoQC configuration file

    master

    When defining file paths in the HistoQC configuration file, note that filenames are resolved relative to the working directory where you execute the command, rather than the base directory of the HistoQC installation.

    To avoid path resolution errors, you should either:

    1. Use absolute paths for all input files.
    2. (Preferred) Run histoqc from the HistoQC directory and provide the remote location or relative path of the input files from that execution context.
  11. Install HistoQC using pip

    master

    For development or customization, you can install HistoQC from source using pip. It is recommended to use a Python virtual environment to manage dependencies.

    Follow these steps:

    1. Clone the repository.
    2. (Optional) Create and activate a virtual environment.
    3. Install the package using pip install ..
    4. Verify the installation by running histoqc --help.
    # 1. Clone the repository
    git clone https://github.com/choosehappy/HistoQC.git
    cd HistoQC
    
    # 2. (Optional) Set Up a Virtual Environment
    python3 -m venv venv
    source venv/bin/activate
    
    # 3. Install HistoQC
    pip install .
    
    # 4. Verify Installation
    histoqc --help