Ashwin Samudre, Guang Gao, Ben Cardoen, Bharat Joshi, Ivan Robert Nabi, Ghassan Hamarneh
Publication: https://www.nature.com/articles/s42003-025-08892-1 (Nature Communications Biology)
nERdy is a toolkit for segmenting and analyzing endoplasmic reticulum (ER) networks from microscopy images. It includes:
- nERdy: An image processing method
- nERdy+: A deep learning method
- Quick Start (5 minutes)
- Detailed Installation
- Using nERdy+ (Deep Learning)
- Using nERdy (Image Processing)
- Training on Your Own Data
- Analysis Tools
- Troubleshooting
- Citation
If you just want to try nERdy+ on your images, follow these steps:
Download and install Miniconda from: https://docs.anaconda.com/miniconda/install/
How to check if you have Conda:
conda --versionIf you see a version number (e.g., conda 23.5.0), you're good! If you get an error, install Miniconda first.
git clone https://github.com/NanoscopyAI/nERdy.git
cd nERdyOr download the ZIP file from GitHub and extract it.
Copy and paste these commands one at a time:
# Create a new environment (this avoids conflicts with other Python projects)
conda create -n nerdy python=3.10 -y
# Activate the environment
conda activate nerdy
# Install PyTorch (for GPU - recommended if you have an NVIDIA GPU)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
# OR install PyTorch for CPU only (if you don't have a GPU)
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# Install other requirements
pip install -r requirements.txtExpected output after last command:
Successfully installed numpy-1.23.1 pandas-2.0.0 ...
python -c "import torch; print('PyTorch works!'); print(f'GPU available: {torch.cuda.is_available()}')"Expected output:
PyTorch works!
GPU available: True (or False if using CPU)
python examples/run_inference.py --input path/to/your/image.pngWhat happens:
- The script loads your image
- Runs the nERdy+ neural network
- Saves a segmentation mask as
your_image_segmentation.png
| Component | Minimum | Recommended |
|---|---|---|
| Python | 3.8 | 3.10 |
| RAM | 8 GB | 16 GB |
| GPU | None (CPU works) | NVIDIA with 4+ GB VRAM |
| Storage | 2 GB | 5 GB |
- Install Miniconda
- Open "Anaconda Prompt" from the Start menu
- Follow the Quick Start steps above
- Install Miniconda
- Open Terminal
- Follow the Quick Start steps above
- Note: Mac does not support CUDA. Use the CPU version of PyTorch.
Follow the Quick Start steps in a terminal.
Run this test to ensure everything is working:
# Make sure you're in the nERdy folder and environment is active
conda activate nerdy
# Test imports
python -c "
import torch
import numpy as np
from PIL import Image
print('All imports successful!')
print(f'PyTorch version: {torch.__version__}')
print(f'NumPy version: {np.__version__}')
"nERdy+ is a neural network that segments ER structures from microscopy images. This is the recommended method for most users as it provides the best results.
# Run on a single image
python examples/run_inference.py --input your_image.png
# Specify output location
python examples/run_inference.py --input your_image.png --output result.png
# Force CPU usage (if GPU causes issues)
python examples/run_inference.py --input your_image.png --device cpu- Format: TIFF
- Type: Grayscale (the script converts color images automatically)
- Size: Any size works, but 128x128 to 1024x1024 is typical
The output is a binary segmentation mask where:
- White (255): ER structure detected
- Black (0): Background
To process a folder of images, use this Python script:
import os
import subprocess
input_folder = "path/to/your/images"
output_folder = "path/to/results"
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(input_folder):
if filename.endswith(('.png', '.tif', '.tiff', '.jpg')):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, f"{filename}_seg.png")
subprocess.run([
"python", "examples/run_inference.py",
"--input", input_path,
"--output", output_path
])
print(f"Processed: {filename}")import sys
sys.path.append('nERdy+') # Add nERdy+ to Python path
import torch
from PIL import Image
from torchvision import transforms
from model import D4nERdy
from postprocessing import postprocessing
# Load the pre-trained model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = D4nERdy(in_channels=1, out_channels=1)
model.load_state_dict(torch.load('nERdy+/NNet_groupy_p4m_v2_VecAdam.pth', map_location=device))
model = model.to(device)
model.eval()
# Load and process your image
image = Image.open('your_image.png').convert('L') # Convert to grayscale
transform = transforms.Compose([transforms.ToTensor()])
image_tensor = transform(image).unsqueeze(0).to(device)
# Run inference
with torch.no_grad():
output = model(image_tensor)
prob_map = torch.sigmoid(output).cpu().squeeze().numpy()
# Post-process to get binary mask
segmentation = postprocessing(prob_map)
# Save result
Image.fromarray(segmentation.astype('uint8')).save('segmentation.png')nERdy is a traditional image processing method that uses morphological operations and vesselness filtering. It requires MATLAB but provides an interpretable pipeline.
| Use nERdy when... | Use nERdy+ when... |
|---|---|
| You have MATLAB available | You want best accuracy |
| You want interpretable results | You don't have MATLAB |
| You need to tune parameters manually | You prefer pre-trained models |
- MATLAB R2021a or later with Image Processing Toolbox
- MATLAB Engine API for Python
First, find your MATLAB installation path:
- Windows:
C:\Program Files\MATLAB\R2023a - Mac:
/Applications/MATLAB_R2023a.app - Linux:
/usr/local/MATLAB/R2023a
Then install the MATLAB Engine:
# Navigate to MATLAB's Python engine folder
cd "<your_matlab_path>/extern/engines/python"
# Install (may need admin/sudo)
python setup.py installVerify installation:
python -c "import matlab.engine; print('MATLAB Engine installed successfully!')"# Make sure you're in the nERdy folder
cd nERdy
# Run on your image
python nerdy_runner.py path/to/your/image.pngThe pipeline has two stages:
Stage 1: Python Preprocessing (preprocess function)
- Normalizes image to [0, 1] range
- Applies CLAHE (Contrast Limited Adaptive Histogram Equalization)
- Area opening to remove small bright artifacts
- Erosion to thin structures
- Local thresholding
Stage 2: MATLAB Vessel Enhancement (Vessel2d.m)
- Applies Jerman's vesselness filter at multiple scales (σ = 0.5 to 2.5)
- Enhances tubular structures
- Binarizes the result
After running, you'll get:
preprocessed_<filename>- Image after Python preprocessingpreprocessed_<filename>_enhance.png- Final segmentation result
# If your image is called "er_sample.png"
cd nERdy
python nerdy_runner.py er_sample.png
# Output files:
# - preprocessed_er_sample.png (intermediate)
# - preprocessed_er_sample_enhance.png (final result)"No module named 'matlab.engine'"
- MATLAB Engine is not installed
- Follow Step 1 above to install it
"MATLAB session cannot be started"
- Make sure MATLAB is properly installed and licensed
- Try running MATLAB manually first to verify it works
"Image Processing Toolbox not found"
- Install the Image Processing Toolbox in MATLAB
- In MATLAB: Home → Add-Ons → Get Add-Ons → Search "Image Processing Toolbox"
If you have your own annotated ER images, you can train a custom model.
Organize your data like this:
my_dataset/
train/
images/
image001.png
image002.png
...
masks/
image001_mask.png
image002_mask.png
...
Important:
- Mask filenames must match image filenames with
_maskadded - Masks should be binary (0 for background, 255 for ER)
- Images should be grayscale
Edit nERdy+/config.ini:
[TRAIN]
seed = 34
lr = 1e-3
betas = 0.9, 0.999
eps = 1e-08
split_ratio = 0.8
bs = 16 # Reduce if you run out of GPU memory
epochs = 100
[MODEL]
in_channels = 1
out_channels = 1
save_path = my_trained_model.pth
[DATA]
dataset_path = /full/path/to/my_datasetcd nERdy+
python train.py --config config.iniWhat to expect:
- Training progress will print after each epoch
- Training 100 epochs takes ~30 minutes on a GPU, ~2-3 hours on CPU
- The model is saved to the path specified in config.ini
python examples/run_inference.py --input test_image.png --model nERdy+/my_trained_model.pthnERdy includes tools for analyzing ER network properties.
Analyze junction dynamics from time-series data:
from analysis.junction_analysis import JunctionAnalysis
# Initialize for your microscopy type
ja = JunctionAnalysis('confocal') # or 'sted'Visualize segmentation and graph metrics:
from analysis.graph_metrics_plotter import GraphMetricsPlotter
from analysis.segmentation_metrics_plotter import SegmentationMetricsPlotter
# Graph metrics
gmp = GraphMetricsPlotter('confocal')
gmp.plot()
# Segmentation metrics
smp = SegmentationMetricsPlotter()
smp.get_segmentation_perf()Download the dataset used in our paper from Figshare.
Cause: PyTorch is not installed or the conda environment is not activated.
Solution:
conda activate nerdy
pip install torch torchvisionCause: Your GPU doesn't have enough memory.
Solutions:
- Use CPU instead:
--device cpu - Reduce batch size in config.ini:
bs = 8orbs = 4 - Process smaller image crops
Cause: Python can't find the nERdy+ modules.
Solution: Make sure you're running from the nERdy root folder:
cd /path/to/nERdy
python examples/run_inference.py --input image.pngCause: The pre-trained model file is missing.
Solution: Make sure you downloaded/cloned the complete repository including the .pth file.
Possible causes and solutions:
- Image quality: nERdy+ works best on high-contrast ER images
- Image type: Make sure your image is grayscale microscopy data
- Different microscopy: If results are poor, consider training on your own data
Cause: Apple Silicon Macs may have issues with GPU acceleration.
Solution: Use CPU mode:
python examples/run_inference.py --input image.png --device cpu- Check that all requirements are installed:
pip install -r requirements.txt - Try creating a fresh conda environment
- Open an issue on GitHub with:
- Your operating system
- Error message (full text)
- Steps you followed
nERdy/
├── nERdy/ # Image processing method (requires MATLAB)
├── nERdy+/ # Deep learning method (recommended)
│ ├── model.py # Neural network architecture
│ ├── train.py # Training script
│ ├── inference.py # Inference utilities
│ ├── config.ini # Training configuration
│ └── NNet_groupy_*.pth # Pre-trained model weights
├── analysis/ # Analysis and visualization tools
├── examples/ # Ready-to-use example scripts
├── test/ # Unit tests
├── figures/ # Documentation images
└── requirements.txt # Python dependencies
If you use nERdy in your research, please cite:
@article{samudre2025nerdy,
title={nERdy: network analysis of endoplasmic reticulum dynamics},
author={Samudre, Ashwin and Gao, Guang and Cardoen, Ben and Joshi, Bharat and Nabi, Ivan Robert and Hamarneh, Ghassan},
journal={Communications Biology},
volume={8},
number={1},
pages={1529},
year={2025},
publisher={Nature Publishing Group UK London}
}
