Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

HCR Analysis Pipeline - Complete Guide

Author: Jane Ling (jane.ling@kcl.ac.uk), Fursham Hamid(fursham.hamid@kcl.ac.uk)

Affiliation: Bioinformatics Core, Centre for Developmental Neurobiology, King's College London

Last updated: March 2026


📋 Contents


What is This?

This is a step-by-step pipeline to analyze Hybridization Chain Reaction (HCR) images of C. elegans. It automatically detects RNA spots in your microscopy images and counts them inside specific cells. The pipeline is designed for multi-channel z-stacks.

The pipeline consists of 3 main steps:

  1. Detect RNA spots using image analysis
  2. Define cell boundaries manually
  3. Count spots in cells automatically

Before You Start

What You'll Need

  • MATLAB (free trial available at mathworks.com, or check if your institute has a campus-wide matlab license)
  • ImageJ/FIJI (free software: imagej.net)
  • RS-FISH plugin in ImageJ(free plugin: installation instructions can be found on the RS-FISH GitHub page)
  • Your HCR microscopy images (in any format supported by bioformats) or example images in this link
  • Excel or similar spreadsheet program

STEP-BY-STEP INSTRUCTIONS

STEP 1: Detect RNA Spots

This step automatically finds all the small dots (RNA spots) in your images.

What You Need:

  • Your raw HCR image (in any format supported by bioformats)
  • The file RS_macro.ijm (in the scripts folder)
  • RS-FISH plugin installed in FIJI

How to Do It:

  1. Open ImageJ/FIJI

    • Click the ImageJ/FIJI icon
    • Wait for it to load (it may take a moment)
  2. Split Multi-Channel Images (If Your Image Has Multiple Fluorescent Colors)

    If your image contains multiple color channels (e.g., red, green, blue spots), you need to separate them first.

    Steps to Split Channels:

    a. Open your image in FIJI:

    • Go to Menu: FileOpen
    • Select your HCR image file (.czi or .tif)

    b. Split the image into individual channels:

    • Go to Menu: ImageColorSplit Channels
    • FIJI will create separate image windows for each color channel
    • Each channel window will be titled with "C1", "C2", "C3", etc. (or the actual color names)

    What You Should See:

    • After splitting, you'll have separate image windows for each channel
    • For example:
      • "C1-red" for your first fluorescent dye
      • "C2-green" for your second fluorescent dye
      • "C3-blue" for your third fluorescent dye

    Note: If your image is already single-channel, skip this step

  3. Open the RS-FISH Analysis Script

    • Go to Menu: FileOpen
    • Find and open RS_macro.ijm
    • You'll see some code in the script window
  4. Customize Paths and Configurations

    • Find the section that says // CONFIGURATION - MODIFY THESE SETTINGS FOR YOUR EXPERIMENT
    • Follow the instructions to modify the settings
  5. Find Optimal RS-FISH Parameters

    • For each channel, follow the instructions in the RS-FISH GitHub to find the anisotropy coefficient and optimal parameters
    • This ensures accurate spot detection for your specific images
    • In the script RS_macro.ijm, Find the section that says // RS-FISH CHANNEL PARAMETERS - MODIFY THESE SETTINGS FOR YOUR EXPERIMENT
    • Follow the instructions to modify the settings
  6. Run the Script

    • Click the "Run" button (green play icon)
    • Watch it process your images
    • Results will be saved to your output folder
  7. What Happens:

    • Creates separate TIFF files for each color channel (if not already split)
    • Automatically finds RNA spots in each channel
    • Saves results to files named RadialSymmetry_results_C1-*.csv, RadialSymmetry_results_C2-*.csv, etc.
  8. Check RS-FISH Results (Optional)

    • It is recommended to check the batch-processing results using the Show Detections function in ImageJ

STEP 2: Manually Draw Cell Boundaries

Now you need to tell the computer which cells you want to analyze and their location in the image. This is the most time-consuming step, but it's important to be accurate.

What You Need:

  • Your raw HCR images open in ImageJ
  • Excel or Google Sheets
  • Patience!

How to Do It:

  1. Create an Excel File Called cell_selection.xlsx

  2. Add These Column Headers (First Row): | FileName | cellNum | z1 | z2 | cell_Identity |

  3. Open Your Image in ImageJ

    • FileOpen
    • Select your raw image file
  4. Select the Freehand Drawing Tool

    • In the toolbar, click the lasso/polygon icon (looks like a rope)
    • This lets you manually draw boundaries
  5. Draw the Cell Boundary

    • Carefully click around the edge of your first target cell
    • Click back at your starting point to close the shape
    • The boundary is now selected (yellow outline)
  6. Save This Boundary

    • Go to EditSelectionAdd to Manager
    • The boundary appears in the "ROI Manager" window on the right
  7. Fill in Each Row of the Excel:

    • FileName: The exact name of your image file (with extension: Image_001.czi)
    • cellNum: Cell number (1, 2, 3, or 4) - matches the cell number in ImageJ
    • z1: The lowest Z-slice number where the cell appears
    • z2: The highest Z-slice number where the cell appears (For this pipeline, it doesn't matter if the values in z1 and z2 are reversed.)
    • cell_Identity: Cell name (e.g., ASIL, ASIR, ASJL, ASJR)

    Example:

    daf-2_sample.czi    1    4.0    14.0    ASIL
    daf-2_sample.czi    2    4.0    14.0    ASIR
    daf-2_sample.czi    3    5.0    15.0    ASJL
    daf-2_sample.czi    4    5.0    15.0    ASJR
    
  8. Repeat for All Target Cells

    • Draw the next cell boundary
    • Add it to the ROI Manager
    • Add it to the excel spreadsheet
    • Repeat until all cells are drawn
  9. Use the Provided Script to Export

    • Once all cell boundaries for one image are drawn, open this script in FIJI:
      • File → Open → export_ROIs_as_csv.ijm
    • Modify the file path to your output folder
    • Click Run
    • This creates files like: XY_imagename_1.csv, XY_imagename_2.csv, etc.
  10. Repeat for all Images

  • Repeat the above steps for all images.
  • Note that as long as the image names does not repeat, all the information can be saved in one spreadsheet and the cell boundaries can be saved in one folder.

STEP 3: Count Spots in Cells - Automated!

This is the final step - the computer does all the work!

What You Need:

  • MATLAB installed and open (R2018b or later recommended)
  • Image Processing Toolbox for MATLAB
  • The files created from Steps 1-2

How to Do It:

  1. Copy Required Files to Your Project Directory

    • Copy these files from the GitHub scripts folder to your project directory:
      • CountRNAinCells.m (main script - do NOT modify)
      • config.m (configuration file - customize this)
      • inhull.m (helper function)
  2. Open config.m in MATLAB

    • Right-click on config.m
    • Click "Open"
    • This opens a configuration file with all the settings
  3. Update Essential Settings

    • Modify these paths to match your folder structure:
      ops.filedir = '../originals/data/Your_Dataset/imagej_cell_boundaries/';
      ops.savedir = '../outputs/Your_Dataset/';
      ops.cell_list_path = '../outputs/Your_Dataset/cell_selection.xlsx';
  4. Configure Channels and Cell Identity

    • Update channel numbers and names if different:
      ops.channels = [1, 2, 3];                         % Channel numbers
      ops.channel_names = {'ins6', 'ins4', 'daf28'};    % Descriptive names
      ops.cell_id = {'ASIL', 'ASIR', 'ASJL', 'ASJR'};  % Must match your Excel file
  5. Adjust Processing Parameters (Optional)

    • Fine-tune detection parameters:
      ops.saturation_threshold = 250;  % Flag spots above this intensity
      ops.tol = 0;                     % Tolerance for point-in-hull test
      ops.verbose = true;              % Show detailed output
  6. Run the Main Script

    • In MATLAB, click the green "Run" button
    • Watch the Command Window for progress messages
  7. Check Your Results

    • Look in your output folder for:
      • stats.csv ← Open this in Excel to see final results!
      • cell_stats.mat ← MATLAB data file with all structure data
  8. Understanding Your Results

    • Open stats.csv in Excel
    • Each row represents one image
    • Column structure:
      • FileName, cellNum, z1, z2, cell_Identity: Basic info
      • [CELLID]_[MARKER]: Spot count (e.g., ASIL_ins6 = spots in ASIL on ins6 channel)
      • [CELLID]_[MARKER]_saturated: Boolean flag if spots exceeded saturation threshold

Key Configuration Details

File Naming Convention:

  • The script expects specific file naming patterns
  • If your files don't follow these patterns, adjust in config.m:
    ops.rs_prefix = 'RadialSymmetry_results';  % Spot detection results prefix
    ops.xy_prefix = 'XY_';                     % Cell boundary file prefix

Important Note on config.m:

  • Do NOT modify CountRNAinCells.m directly
  • All customization must be done in config.m
  • If you need algorithmic changes, create a new version (e.g., CountRNAinCells_v2.m) and keep the original as reference

TROUBLESHOOTING 🔧

Disclaimer: The troubleshooting section was generated by AI and solutions suggested were not tested.

Step 1 (RS-FISH Detection) Issues

"Warning: RS-FISH file not found"

  • Fix: Make sure the files RadialSymmetry_results_C1-*.csv are in your output folder
  • Check that Step 1 completed successfully
  • Verify file naming: should be RadialSymmetry_results_C[channel]-[image_name].tif.csv

"The image opened but it looks weird" or "Channel colors seem wrong"

  • Fix: If the image appears incorrectly, it may not have been opened properly
    • Close the image and try again
    • FIJI should auto-detect the file format if it's a standard bioformats-compatible file
    • If colors look strange, you may need to adjust the display settings (Brightness/Contrast)

"I split the channels but they don't look right"

  • Possible solutions:
    1. The channels may be in different image windows - click between them to check all channels
    2. After splitting, one window will be active - check the title bar to see which channel you're looking at
    3. If the split didn't work: try _ProcessSplit Channels instead of _ColorSplit Channels
    4. If channels look misaligned, make sure your microscope calibration is correct

"I'm not sure if channel splitting worked correctly"

  • Verification steps:
    1. After splitting, you should have multiple image windows open (one per channel)
    2. Each window title should show "C1", "C2", "C3" (or color names like "red", "green", "blue")
    3. Merge the channels back together (ImageColorMerge Channels) to verify alignment
    4. If all channels overlap perfectly, splitting was successful

Step 2 (Cell Boundary) Issues

"Error: Cell list file not found"

  • Fix: Make sure cell_selection.xlsx is saved in your output folder with the exact name
  • Verify the Excel file has the required columns: FileName, cellNum, z1, z2, cell_Identity

Step 3 (CountRNAinCells) Issues

"Error: Cell boundary directory not found"

  • Fix: Check the path in config.m and make sure it exactly matches your folder names
  • Use forward slashes / even on Windows, not backslashes
  • The path should point to the folder containing XY_*.csv files
  • Consider using absolute paths if relative paths don't work

"No spots are being counted (all zeros)"

  • Check these in order:
    1. Verify RadialSymmetry_results_C[channel]-*.csv files exist in your output folder
    2. Check that channel numbers in ops.channels match the filenames (e.g., if your file says C1, channels should include 1)
    3. Check that the Z-ranges in cell_selection.xlsx (z1, z2) encompass actual spot locations
    4. Verify your cell boundaries in ImageJ are drawn correctly
    5. Enable verbose output: ops.verbose = true; to see detailed processing steps

"Error: No matching RS-FISH results found"

  • Fix: Ensure RadialSymmetry_results_C[channel]-*.csv files exist in ops.savedir
  • Verify channel numbers in ops.channels match the file names
  • Check that base filenames match between RS-FISH results and cell selection file

"Missing output files" or script runs but no results appear

  • Check that ops.savedir directory has write permissions
  • If the script runs but produces no output, check the MATLAB variable explorer for the stats structure
  • Enable verbose output to see what's happening: ops.verbose = true;

"I'm getting warnings about file not found"

  • Verify all paths in config.m end with the correct file separator / (forward slash) or / (backward slash) for your computer
  • Make sure cell_selection.xlsx contains entries matching your image filenames
  • Check that ImageJ_cell_boundaries folder exists and contains your XY_*.csv files

I need more detailed output for debugging

  • In config.m, enable verbose mode:
    ops.verbose = true;  % change from false to true
  • This will print detailed information as the script runs, helping you identify where issues occur

GETTING MORE HELP

For ImageJ/FIJI Questions:

For MATLAB Questions:

  • MATLAB Help: Press F1 in MATLAB
  • Check config.m for detailed inline documentation on all settings

For Pipeline Questions:

  • Raise an issue in the GitHub page, or email the authors, with the debugging checklist below to speed up troubleshooting:

General Information

  • Your operating system (Windows/Mac/Linux)
  • MATLAB version (type version in MATLAB command window)
  • FIJI/ImageJ version (Help → About ImageJ)
  • RS-FISH plugin version

For Step 1 Issues (RS-FISH Detection)

  • Image file format (.czi, .tiff, etc.)
  • Number of channels in your image
  • Image dimensions (X, Y, Z)
  • Complete error message from FIJI
  • Did RadialSymmetry_results_*.csv files get created? (List filenames)
  • RS-FISH parameters used for each channel (anisotropy coefficient, etc.)
  • Log file or console output from FIJI (RS_processing_summary.txt)

For Step 2 Issues (Cell Boundary Definition)

  • What is the exact filename of your cell_selection.xlsx?
  • List the column headers in your Excel file
  • Sample row from the Excel file
  • How many cells were drawn and for which images?
  • Did XY_*.csv files get created? (List filenames)
  • Are XY_*.csv files in the correct folder? (Show folder path)

For Step 3 Issues (CountRNAinCells)

  • MATLAB version (type version)
  • Do you have the Image Processing Toolbox? (type ver ImageProcessing in MATLAB)
  • Full error message from MATLAB (copy the red text from command window)
  • Your complete config.m file contents (or at least the paths):
    ops.filedir = ?
    ops.savedir = ?
    ops.cell_list_path = ?
    ops.channels = ?
    ops.channel_names = ?
  • List of files that exist in ops.filedir (cell boundaries folder)
  • List of files that exist in ops.savedir (output folder)
  • Did you enable verbose output? If so, paste the command window output
  • File NOT found error? Show the exact file path it's looking for

Directory/File Structure to Verify

  • Can you access the folders from your computer? (Try manually navigating there)
  • Are file paths using / (forward slash) consistently?
  • Do file names match exactly? (Check capitalization, spaces, spelling)
  • Sample filenames:
    • Cell boundary files: XY_?_?.csv
    • RS-FISH results: RadialSymmetry_results_C?-?
    • Excel file: cell_selection.xlsx
    • Image files: ?

Information to Include When Posting Issues

When reporting a problem, please include:

  1. One-line description of the problem
  2. Which step is failing (Step 1, 2, or 3)
  3. Exact error message (copy-paste from software)
  4. What you've already tried to fix it
  5. Screenshots if the issue involves how something looks
  6. Relevant files (Excel file, config.m, log files) if possible
  7. Your folder and file structure (show paths and filenames)

QUICK REFERENCE

Files You Create:

File Where Created By Contains
Individual channel TIFFs outputs/ FIJI macro (Step 1) Separate images for each color
RadialSymmetry_results_C1/2/3.csv outputs/ FIJI macro (Step 1) X, Y, Z, intensity of spots
cell_selection.xlsx outputs/ You (Step 2) Image names, cell IDs, Z-ranges
XY_*.csv outputs/ You + FIJI macro (Step 2) Coordinates of cell boundaries
stats.csv outputs/ MATLAB script (Step 3) Your final results!

Directory Structure You Need:

project_folder/
├── originals/                (You can also have images in subfolders.)
│   ├── image_1.czi
│   ├── image_2.czi
│   └── ...
├── outputs/                  (Folder structure will follow that in the originals.)
│   ├── image_1               (created in Step 1)
│   │   ├── C1-image_1.tif
│   │   ├── C2-image_1.tif
│   │   ├── C3-image_1.tif
│   │   ├── C4-image_1.tif
│   │   ├── MASK_image_1.tif
│   │   ├── RadialSymmetry_results_C1-image_1.tif.csv
│   │   ├── RadialSymmetry_results_C2-image_1.tif.csv
│   │   └── RadialSymmetry_results_C3-image_1.tif.csv
│   ├── image_2
│   │   └── ...
│   ├── imagej_cell_boundaries/     (created in Step 2)
│   │   ├── XY_image_1_1.csv
│   │   ├── XY_image_1_2.csv
│   │   └── ...
│   ├── cell_selection.xlsx         (created in Step 2)
│   ├── cell_stats.mat              (created in Step 3)
│   ├── RS_Exe_times.txt            (created in Step 1)
│   ├── RS_processing_summary.txt   (created in Step 1)
│   └── stats.csv                   (created in Step 3 - your results!)
└── scripts/                        (downloaded from GitHub)
    ├── CountRNAinCells.m
    ├── config.m
    ├── inhull.m
    ├── RS_macro.ijm
    └── export_ROIs_as_csv.ijm

KEY ABBREVIATIONS

Abbreviation Means
HCR Hybridization Chain Reaction (RNA detection method)
RS-FISH Radial Symmetry FISH (spot detection algorithm)
CSV Comma-Separated Values (simple spreadsheet file)
ROI Region of Interest (cell boundary)
Z-range The depth in the microscope stack where something appears
Cell ID Name/identity of the cell (e.g., ASIL = "ASI Left")

SUCCESS! What's Next?

Now that you have stats.csv with your spot counts:

  1. Open in Excel to view and export data
  2. Further analysis in R, Python, or GraphPad
  3. Plot results to show spot distribution across cells and genes

BONUS: Visualize Your Results in 3D

Want to see your cell boundaries and RNA spots in 3D? Use napari for fast, interactive visualization!

Why napari instead of MATLAB?

  • 10-20x faster 3D rendering
  • No license required (free & open-source)
  • Real-time interactive rotation and zoom
  • 5-minute setup with conda

Installation

The environment setup files are located in the scripts/ directory:

Option 1: Automated Setup (Recommended)

For Linux/macOS:

cd scripts/
bash setup_hcr_env.sh

For Windows/Linux/macOS (cross-platform):

python scripts/setup_hcr_env.py

The setup script will:

  • ✅ Check for conda installation
  • ✅ Create the hcr_env environment with all required packages
  • ✅ Install napari, PyQt5, and all visualization dependencies
  • ✅ Verify the installation

Option 2: Manual Setup

# Create environment from YAML file
conda env create -f scripts/hcr_env.yml

# Activate the environment
conda activate hcr_env

Quick Start

# After environment is created, activate it:
conda activate hcr_env

# Run the visualization script:
bash scripts/run_visualization.sh

# Or run with specific parameters:
python scripts/napari_load_and_visualize.py \
  --data-dir outputs \
  --image-name "N2_ins-6_488_ins-4_546_daf-28_647_DAPI_PAPER.8"

What's Included

The hcr_env environment includes:

  • napari (0.7.0) - 3D visualization framework
  • PyQt5 - GUI framework for napari
  • vispy - GPU-accelerated visualization
  • numpy, pandas, scipy - Scientific computing
  • tifffile, imageio - Image I/O
  • dask - Parallel computing
  • And all other dependencies for visualization

Setup Documentation

For complete setup instructions, troubleshooting, and platform-specific guides:

👉 Read: scripts/ENVIRONMENT_SETUP.md

This guide includes:

  • Detailed installation steps for different operating systems
  • Troubleshooting common issues
  • Environment verification procedures
  • Manual installation alternatives
  • System requirements

About

This is a step-by-step pipeline to analyze Hybridization Chain Reaction (HCR) images of C. elegans. It automatically detects RNA spots in your microscopy images and counts them inside specific cells. The pipeline is designed for multi-channel z-stacks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages