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 🐍🔬
Metadata
Release files for templatematchingpy 1.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| templatematchingpy-1.0.3.tar.gz | 18.5 MB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| templatematchingpy-1.0.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 18.5 MB
Release files / templatematchingpy-1.0.3.tar.gz
| Download URL | templatematchingpy-1.0.3.tar.gz |
|---|---|
| Size | 18.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9af3875bd8846641bc2f090b51af4b69b47753cfe64a4a28fe7e97fbe0b544d1
|
|
BLAKE2b-256 checksum How to use checksums |
3d86d704205c1e1c790ecf29a57114d5037415a139ab6094bb6e1ffbd05588f5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jan 15, 2026.
Transparency logRelease files / templatematchingpy-1.0.3-py3-none-any.whl
| Download URL | templatematchingpy-1.0.3-py3-none-any.whl |
|---|---|
| Size | 19.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
db5be94c7e5281bc3f1f279f0fea69790a6389ab6cbfac4669a84d8535ba3f36
|
|
BLAKE2b-256 checksum How to use checksums |
35287660717708894f73aa4907c95dc8dd075d2425c0a36bdc94ea5fc465df4e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jan 15, 2026.
Transparency log