Python implementation of ImageJ template matching and stack alignment
Project description
TemplateMatchingPy
TemplateMatchingPy is a Python implementation of the popular ImageJ/Fiji template matching and stack alignment plugins originally developed by Qingzong Tseng, providing a programmatic, GUI-free interface for template matching and image stack alignment with sub-pixel precision designed specifically for microscopy workflows. Key features include multiple OpenCV correlation methods (TM_SQDIFF, TM_CCORR, TM_CCOEFF variants), sub-pixel precision through Gaussian peak fitting for enhanced alignment accuracy, and flexible configuration options including customizable search areas, interpolation methods, and precision settings.
This registration package is limited to Translation operations (Movements in the X-Y axis), which makes it suitable for registering time-lapses where the main image is drifting. It helps stabilising the image across time-frames. Below you can see a demostration of the capabilities of this package:
Installation
pip install git+https://github.com/yourusername/TemplateMatchingPy.git
Or you can also build form source:
git clone https://github.com/yourusername/TemplateMatchingPy.git
cd TemplateMatchingPy
pip install -e .
Dependencies
- Python ≥ 3.7
- NumPy ≥ 1.19.0
- OpenCV ≥ 4.5.0
Basic Usage
import numpy as np
from templatematchingpy import (
register_stack,
AlignmentConfig,
create_test_image_stack,
calculate_alignment_quality,
)
# Create test image stack (or load your own)
image_stack, true_displacements = create_test_image_stack(
n_slices=8, height=256, width=256, translation_range=5.0, noise_level=0.1
)
# Define template region (x, y, width, height)
bbox = (100, 100, 64, 64)
# Configure alignment
config = AlignmentConfig(method=5, subpixel=True)
# Perform alignment
aligned_stack, displacements = register_stack(
image_stack=image_stack,
bbox=bbox,
reference_slice=0,
config=config
)
print(f"Aligned {len(displacements)} slices")
print(f"Mean displacement: {np.mean([np.sqrt(dx**2 + dy**2) for dx, dy in displacements]):.2f} pixels")
Working with Files
import cv2
import numpy as np
from templatematchingpy import register_stack, AlignmentConfig
# Load multi-page TIFF stack
ret, images = cv2.imreadmulti("./examples/data/example_image_stack.tiff", flags=cv2.IMREAD_GRAYSCALE)
if not ret:
raise ValueError("Could not load TIFF stack")
# Convert list of images to 3D numpy array [frames, height, width]
image_stack = np.array(images, dtype=np.float32)
# Normalize to [0, 1] range if needed
if image_stack.max() > 1.0:
image_stack = image_stack / 255.0
print(f"Loaded stack with shape: {image_stack.shape}")
# Get image dimensions and calculate centered bbox
height, width = image_stack.shape[1], image_stack.shape[2]
box_width = 1200
box_height = 1200
x = (width - box_width) // 2
y = (height - box_height) // 2
# Define template region (x, y, width, height)
bbox = (x, y, box_width, box_height)
# Configure and perform alignment
config = AlignmentConfig(method=5, subpixel=True)
aligned_stack, displacements = register_stack(
image_stack, bbox=bbox, reference_slice=0, config=config
)
# Save aligned stack as float32 multi-page TIFF
# OpenCV requires list of individual frames for multi-page TIFF
aligned_frames = [frame.astype(np.float32) for frame in aligned_stack]
cv2.imwritemulti("aligned_stack.tiff", aligned_frames)
print(f"Alignment completed with {len(displacements)} slices")
print(f"Displacements: {displacements}")
Configuration Options
AlignmentConfig Parameters
from templatematchingpy import AlignmentConfig
import cv2
config = AlignmentConfig(
method=5, # Template matching method (0-5)
search_area=0, # Search area in pixels (0 = full image)
subpixel=True, # Enable sub-pixel precision
interpolation=cv2.INTER_LINEAR # Interpolation method
)
Template Matching Methods
| Method | OpenCV Constant | Description | Best For |
|---|---|---|---|
| 0 | TM_SQDIFF | Squared Difference | High contrast templates |
| 1 | TM_SQDIFF_NORMED | Normalized Squared Difference | Robust matching |
| 2 | TM_CCORR | Cross Correlation | Bright templates |
| 3 | TM_CCORR_NORMED | Normalized Cross Correlation | Illumination invariant |
| 4 | TM_CCOEFF | Correlation Coefficient | General purpose |
| 5 | TM_CCOEFF_NORMED | Normalized Correlation Coefficient | Recommended |
License
This project is licensed under the European Union Public Licence v. 1.2 (EUPL-1.2) - see the LICENSE file for details.
Acknowledgments
- Qingzong Tseng: Original ImageJ Template Matching plugin author
- Laurent Thomas & Jochen Gehrig: Multi-Template Matching ImageJ plugin
- ImageJ/Fiji Community: Foundational image analysis tools
- OpenCV Contributors: Computer vision library
Citation
If you use TemplateMatchingPy in your research, please cite:
@software{templatematchingpy,
title={TemplateMatchingPy: Python implementation of ImageJ template matching and stack alignment},
author={TemplateMatchingPy Santiago Cano Muniz},
year={2024},
url={https://github.com/phisanti/TemplateMatchingPy}
}
This implementation is based on the template matching methods described in the original research:
- Thomas, L. & Gehrig, J. Multi-template matching: a versatile tool for object-localization in microscopy images. BMC Bioinformatics 21, 44 (2020). https://doi.org/10.1186/s12859-020-3363-7
- Tseng, Q. et al. A new micropatterning method of soft substrates reveals that different tumorigenic signals can promote or reduce cell contraction levels. Lab on a Chip 11, 2231 (2011).
- Tseng, Q. et al. Spatial Organization of the Extracellular Matrix Regulates Cell–cell Junction Positioning. PNAS (2012). doi:10.1073/pnas.1106377109
- Tseng, Qingzong. 2011. "Study of multicellular architecture with controlled microenvironment". Ph.D. dissertation, Université de Grenoble. http://tel.archives-ouvertes.fr/tel-00622264
Related Projects
- ImageJ: Java-based image processing
- Fiji: ImageJ distribution with plugins
- scikit-image: Python image processing library
- OpenCV: Computer vision library
- Qingzong Tseng github repo
- Laurent Thomas github repo
TemplateMatchingPy - Bringing ImageJ template matching to Python workflows 🐍🔬
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file templatematchingpy-1.0.1.tar.gz.
File metadata
- Download URL: templatematchingpy-1.0.1.tar.gz
- Upload date:
- Size: 97.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
714d2bf22e0647e117290056201f5d70868bf3894dee87df081181970efb3431
|
|
| MD5 |
c3ec7a4aadb00f81c3b7d73cab73a404
|
|
| BLAKE2b-256 |
f6832f720b36330ad3d93c1071ff61b2cbbb97fa5d4cadf342e69f20178f81dd
|
Provenance
The following attestation bundles were made for templatematchingpy-1.0.1.tar.gz:
Publisher:
python-publish.yml on phisanti/TemplateMatchingPy
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
templatematchingpy-1.0.1.tar.gz -
Subject digest:
714d2bf22e0647e117290056201f5d70868bf3894dee87df081181970efb3431 - Sigstore transparency entry: 230242444
- Sigstore integration time:
-
Permalink:
phisanti/TemplateMatchingPy@362093c57dec97413c688498e5c61d0f498578c9 -
Branch / Tag:
refs/heads/master - Owner: https://github.com/phisanti
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@362093c57dec97413c688498e5c61d0f498578c9 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file templatematchingpy-1.0.1-py3-none-any.whl.
File metadata
- Download URL: templatematchingpy-1.0.1-py3-none-any.whl
- Upload date:
- Size: 19.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ff69aed73b8d28b972f89f2635b66859f96d72392e23effce6b75a237404c1b7
|
|
| MD5 |
a009249a03e268821937a7d170ca496e
|
|
| BLAKE2b-256 |
90255c91416fb190f8d20a0188844fa860b1b072bc76650d61c23fd07cd8d2eb
|
Provenance
The following attestation bundles were made for templatematchingpy-1.0.1-py3-none-any.whl:
Publisher:
python-publish.yml on phisanti/TemplateMatchingPy
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
templatematchingpy-1.0.1-py3-none-any.whl -
Subject digest:
ff69aed73b8d28b972f89f2635b66859f96d72392e23effce6b75a237404c1b7 - Sigstore transparency entry: 230242447
- Sigstore integration time:
-
Permalink:
phisanti/TemplateMatchingPy@362093c57dec97413c688498e5c61d0f498578c9 -
Branch / Tag:
refs/heads/master - Owner: https://github.com/phisanti
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@362093c57dec97413c688498e5c61d0f498578c9 -
Trigger Event:
workflow_dispatch
-
Statement type: