Template Matching¶
Class: TemplateMatchingBlockV1
Source: inference.core.workflows.core_steps.classical_cv.template_matching.v1.TemplateMatchingBlockV1
Locate instances of a template image within a larger image using template matching with normalized cross-correlation, finding exact or near-exact matches of the template pattern at any location in the image, outputting bounding box detections with optional NMS filtering for object detection, logo detection, pattern recognition, and template-based object localization workflows.
How This Block Works¶
This block searches for occurrences of a template image within a larger input image using normalized cross-correlation template matching. The block:
- Receives an input image and a template image (smaller pattern to search for)
- Converts both images to grayscale for template matching (template matching typically works on grayscale images for efficiency and robustness)
- Performs template matching using OpenCV's matchTemplate with TM_CCOEFF_NORMED method:
- Slides the template across the input image at every possible position
- Computes normalized cross-correlation coefficient at each position (measures similarity between template and image region)
- Generates a similarity map showing how well the template matches at each location
- Identifies match locations where similarity exceeds the matching_threshold:
- Finds all positions where the correlation coefficient is greater than or equal to the threshold
- Threshold values range from 0.0 to 1.0, with higher values requiring closer matches
- Lower thresholds find more potential matches (including partial matches), higher thresholds find only very similar matches
- Creates bounding boxes for each match:
- Each match location becomes a detection with a bounding box matching the template's dimensions
- All detections have confidence of 1.0 (they met the threshold requirement)
- All detections are assigned class "template_match" and class_id 0
- Each detection gets a unique detection ID for tracking
- Optionally applies Non-Maximum Suppression (NMS) to filter overlapping detections:
- Template matching often produces many overlapping detections at the same location (duplicate matches)
- NMS removes overlapping detections, keeping only the best match in each area
- NMS threshold controls how much overlap is allowed before removing detections
- Can be disabled (apply_nms=False) if NMS becomes computationally intractable with very large numbers of matches
- Attaches metadata to detections:
- Sets parent_id to reference the input image
- Sets prediction_type to "object-detection"
- Stores image dimensions for coordinate reference
- Attaches parent coordinate information for workflow tracking
- Returns detection predictions in sv.Detections format along with the total number of matches found
The block uses normalized cross-correlation which is effective for finding exact or near-exact template matches. It works best when the template appears in the image at the same scale, rotation, and lighting conditions. The method tends to produce many overlapping detections for the same match location, which is why NMS filtering is important. However, in cases with extremely large numbers of matches (e.g., repeating patterns), NMS may become computationally expensive and can be disabled if needed.
Common Use Cases¶
- Logo and Brand Detection: Find specific logos or brand elements within images (e.g., detect company logos in photos, find brand markers in images, locate specific logo patterns in scenes), enabling logo detection workflows
- Exact Pattern Matching: Locate specific patterns or objects that appear identically in images (e.g., find specific UI elements in screenshots, detect exact patterns in images, locate specific visual elements), enabling exact pattern detection workflows
- Quality Control and Inspection: Find reference patterns or features for quality inspection (e.g., detect specific features in manufacturing images, find reference markers for alignment, locate inspection targets), enabling quality control workflows
- Object Localization: Locate specific objects or regions when exact appearance is known (e.g., find specific objects with known appearance, locate reference objects in images, detect specific visual elements), enabling template-based object localization
- Document Processing: Find specific elements or regions in documents (e.g., locate form fields in documents, detect specific document elements, find reference markers in scanned documents), enabling document processing workflows
- UI Element Detection: Detect specific UI components or elements in interface images (e.g., find buttons in UI screenshots, locate specific UI elements, detect interface components), enabling UI analysis workflows
Connecting to Other Blocks¶
This block receives an image and template, and produces detection predictions:
- After image input blocks to find template patterns in input images (e.g., search for templates in input images, locate patterns in camera feeds, find templates in image streams), enabling template matching workflows
- After preprocessing blocks to find templates in preprocessed images (e.g., match templates after image enhancement, find patterns in filtered images, locate templates in normalized images), enabling preprocessed template matching
- Before visualization blocks to visualize template match locations (e.g., visualize detected template matches, display bounding boxes for matches, show template match results), enabling template match visualization workflows
- Before filtering blocks to filter template matches by criteria (e.g., filter matches by location, select specific match regions, refine template match results), enabling filtered template matching workflows
- Before crop blocks to extract regions around template matches (e.g., crop areas around matches, extract match regions for analysis, crop template match locations), enabling template-based region extraction
- In quality control workflows where template matching is used for inspection or alignment (e.g., find reference markers for alignment, detect inspection targets, locate quality control features), enabling quality control template matching workflows
Type identifier¶
Use the following identifier in step "type" field: roboflow_core/template_matching@v1to add the block as
as step in your workflow.
Properties¶
| Name | Type | Description | Refs |
|---|---|---|---|
name |
str |
Enter a unique identifier for this step.. | ❌ |
matching_threshold |
float |
Minimum similarity threshold (0.0 to 1.0) required for a template match. Higher values (closer to 1.0) require very close matches and find fewer but more precise matches. Lower values (closer to 0.0) allow more lenient matches and find more potential matches including partial matches. Default is 0.8, which requires fairly close matches. Use lower thresholds (0.6-0.7) to find more matches or handle slight variations. Use higher thresholds (0.85-0.95) for exact matches only. The threshold compares normalized cross-correlation coefficients from template matching.. | ✅ |
apply_nms |
bool |
Whether to apply Non-Maximum Suppression (NMS) to filter overlapping detections. Template matching often produces many overlapping detections at the same location. NMS removes overlapping detections, keeping only the best match in each area. Default is True (recommended for most cases). Set to False if: (1) the number of matches is extremely large (NMS may become computationally expensive), (2) you want to see all raw matches without filtering, or (3) matches are intentionally close together and should all be kept. When disabled, you may see many duplicate detections for the same match location.. | ✅ |
nms_threshold |
float |
Intersection over Union (IoU) threshold for Non-Maximum Suppression. Only relevant when apply_nms is True. Detections with IoU overlap greater than this threshold are considered duplicates, and only the detection with highest confidence is kept. Lower values (0.3-0.4) are more aggressive at removing overlaps, removing detections that are only slightly overlapping. Higher values (0.6-0.7) are more lenient, only removing heavily overlapping detections. Default is 0.5, which provides balanced overlap filtering. Adjust based on how much overlap you expect between template matches and how close together valid matches can be.. | ✅ |
The Refs column marks possibility to parametrise the property with dynamic values available
in workflow runtime. See Bindings for more info.
Available Connections¶
Compatible Blocks
Check what blocks you can connect to Template Matching in version v1.
- inputs:
Trace Visualization,Twilio SMS Notification,Image Preprocessing,Image Slicer,Dynamic Crop,Bounding Box Visualization,Webhook Sink,Halo Visualization,Mask Visualization,Absolute Static Crop,Pixelate Visualization,Twilio SMS/MMS Notification,SIFT Comparison,Dot Visualization,Stitch Images,OPC UA Writer Sink,Email Notification,Stability AI Inpainting,Frame Delay,Cosine Similarity,Keypoint Visualization,Gaze Detection,Roboflow Custom Metadata,Dynamic Zone,Auto Rotate on Edges,Image Slicer,PTZ Tracking (ONVIF),Circle Visualization,Model Comparison Visualization,Stability AI Outpainting,Slack Notification,Line Counter Visualization,Camera Calibration,Contrast Enhancement,Relative Static Crop,PLC Reader,Clip Comparison,Morphological Transformation,Email Notification,Halo Visualization,VLM As Detector,Polygon Visualization,Camera Focus,Corner Visualization,Ellipse Visualization,PLC Writer,Crop Visualization,Model Monitoring Inference Aggregator,Morphological Transformation,Roboflow Visual Search,Icon Visualization,Heatmap Visualization,Color Visualization,Motion Detection,Detections Consensus,Image Blur,Triangle Visualization,Background Color Visualization,Grid Visualization,Image Contours,Image Threshold,Blur Visualization,Roboflow Visual Search Classifier,QR Code Generator,Reference Path Visualization,Polygon Zone Visualization,Roboflow Asset Library Attributes,Classification Label Visualization,Microsoft SQL Server Sink,Perspective Correction,Background Subtraction,Camera Focus,Image Convert Grayscale,Label Visualization,Contrast Equalization,Polygon Visualization,VLM As Classifier,SIFT,Stability AI Image Generation,Text Display,VLM As Detector,JSON Parser,MQTT Writer,Roboflow Dataset Upload,Local File Sink,Identify Outliers,Identify Changes,Roboflow Vision Events,SIFT Comparison,VLM As Classifier,Event Writer,S3 Sink,Depth Estimation,Roboflow Dataset Upload - outputs:
Image Preprocessing,Time in Zone,Anthropic Claude,Image Slicer,Dynamic Crop,Mask Area Measurement,BoT-SORT Tracker,Bounding Box Visualization,Mask Edge Snap,Object Detection Model,Path Deviation,Absolute Static Crop,SIFT Comparison,Stitch Images,Stitch OCR Detections,Instance Segmentation Model,Email Notification,Stability AI Inpainting,Frame Delay,Distance Measurement,Track Class Lock,Florence-2 Model,Roboflow Custom Metadata,Dynamic Zone,Auto Rotate on Edges,Dominant Color,Detections Transformation,Byte Tracker,Keypoint Detection Model,Stability AI Outpainting,Model Comparison Visualization,Detections Classes Replacement,Slack Notification,Line Counter Visualization,Byte Tracker,SORT Tracker,Camera Focus,Ellipse Visualization,Corner Visualization,Detections List Roll-Up,Morphological Transformation,Anthropic Claude,Roboflow Visual Search,Color Visualization,Instance Segmentation Model,Triangle Visualization,Detection Event Log,Detections Stabilizer,Time in Zone,Object Detection Model,Image Contours,Image Threshold,Detections Merge,QR Code Generator,Roboflow Visual Search Classifier,Florence-2 Model,Stitch OCR Detections,Path Deviation,GeoTag Detection,Label Visualization,Detection Offset,Instance Segmentation Model,Line Counter,MQTT Writer,Roboflow Dataset Upload,Identify Outliers,Event Writer,Byte Tracker,Trace Visualization,Twilio SMS Notification,Pixel Color Count,SAM 3 Interactive,Detections Filter,Object Detection Model,Velocity,Webhook Sink,Halo Visualization,Mask Visualization,Pixelate Visualization,Twilio SMS/MMS Notification,Dot Visualization,Image Stack,OPC UA Writer Sink,OC-SORT Tracker,Keypoint Visualization,Detections Combine,Image Slicer,PTZ Tracking (ONVIF),Time in Zone,Circle Visualization,SAM2 Video Tracker,ByteTrack Tracker,Morphological Transformation,Per-Class Confidence Filter,Email Notification,Halo Visualization,Polygon Visualization,Crop Visualization,Model Monitoring Inference Aggregator,Keypoint Detection Model,Size Measurement,Heatmap Visualization,Icon Visualization,Motion Detection,Detections Consensus,Instance Segmentation Model,Overlap Analysis,Segment Anything 2 Model,Image Blur,Detections Stitch,Background Color Visualization,Grid Visualization,Blur Visualization,Anthropic Claude,Reference Path Visualization,Classification Label Visualization,Perspective Correction,Background Subtraction,Polygon Visualization,Text Display,Roboflow Vision Events,Identify Changes,Keypoint Detection Model,SIFT Comparison,Overlap Filter,Line Counter,Roboflow Dataset Upload
Input and Output Bindings¶
The available connections depend on its binding kinds. Check what binding kinds
Template Matching in version v1 has.
Bindings
-
input
image(image): Large image in which to search for the template pattern. The template will be searched across this entire image at all possible positions. The image is converted to grayscale internally for template matching. Template matching works best when the image and template have similar lighting conditions and the template appears at similar scale and orientation in the image..template(image): Small template image pattern to search for within the input image. The template should be smaller than the input image. The template is converted to grayscale internally for matching. Template matching finds exact or near-exact matches of this template at any location in the input image. Works best when the template appears in the image at the same scale, rotation, and lighting conditions. The template's dimensions determine the size of the detection bounding boxes..matching_threshold(float): Minimum similarity threshold (0.0 to 1.0) required for a template match. Higher values (closer to 1.0) require very close matches and find fewer but more precise matches. Lower values (closer to 0.0) allow more lenient matches and find more potential matches including partial matches. Default is 0.8, which requires fairly close matches. Use lower thresholds (0.6-0.7) to find more matches or handle slight variations. Use higher thresholds (0.85-0.95) for exact matches only. The threshold compares normalized cross-correlation coefficients from template matching..apply_nms(boolean): Whether to apply Non-Maximum Suppression (NMS) to filter overlapping detections. Template matching often produces many overlapping detections at the same location. NMS removes overlapping detections, keeping only the best match in each area. Default is True (recommended for most cases). Set to False if: (1) the number of matches is extremely large (NMS may become computationally expensive), (2) you want to see all raw matches without filtering, or (3) matches are intentionally close together and should all be kept. When disabled, you may see many duplicate detections for the same match location..nms_threshold(float_zero_to_one): Intersection over Union (IoU) threshold for Non-Maximum Suppression. Only relevant when apply_nms is True. Detections with IoU overlap greater than this threshold are considered duplicates, and only the detection with highest confidence is kept. Lower values (0.3-0.4) are more aggressive at removing overlaps, removing detections that are only slightly overlapping. Higher values (0.6-0.7) are more lenient, only removing heavily overlapping detections. Default is 0.5, which provides balanced overlap filtering. Adjust based on how much overlap you expect between template matches and how close together valid matches can be..
-
output
predictions(object_detection_prediction): Prediction with detected bounding boxes in form of sv.Detections(...) object.number_of_matches(integer): Integer value.
Example JSON definition of step Template Matching in version v1
{
"name": "<your_step_name_here>",
"type": "roboflow_core/template_matching@v1",
"image": "$inputs.image",
"template": "$inputs.template",
"matching_threshold": 0.8,
"apply_nms": "$inputs.apply_nms",
"nms_threshold": "$inputs.nms_threshold"
}