Welcome to K230 Vision Module repository
11. Template Matching
Template Matching
Template MatchingPrefaceExample ResultsPrinciple ExplanationWhat is Template MatchingResponse Map and Best PositionCode OverviewInitialize Camera and Display ModuleCreate Template and ThresholdDownsample and BinarizeMatch and Find Best PositionDraw Match BoxPrint Score and Release ResourcesParameter Adjustment Notes
Preface
This tutorial applies to firmware version: CanMV_K230_YAHBOOM_micropython_v1.8-13. You can download it from the Jianan website https://download.kendryte.com/developer/releases/canmv_k230_micropython/daily_build/

Example Results
Run the example code for this section 09.camera_match_template.py.
This section downsamples the live image and applies binarization, uses a fixed 20×20 template for normalized correlation coefficient matching, finds the highest score position via minMaxLoc(), and draws the matching box back onto the original image.

Principle Explanation
What is Template Matching
Template matching slides a small image pixel by pixel across the search image and calculates a similarity score for each position. TM_CCOEFF_NORMED returns the normalized correlation coefficient; the score closer to 1 means the template is more similar to that region.
Template matching is sensitive to scale, rotation, perspective, and appearance changes. The example uses a fixed binary template, suitable for demonstrating the API, but does not represent the ability to recognize arbitrary white targets.
Response Map and Best Position
If the search image size is W×H, the template size is w×h, the response map size is typically:
(W - w + 1) × (H - h + 1)minMaxLoc() returns the minimum value, maximum value, and their positions. For TM_CCOEFF_NORMED, this example uses the maximum value position as the best match point.
Code Overview
Initialize Camera and Display Module
xxxxxxxxxxW, H = 640, 480sensor = Sensor(width=1280, height=960, fps=90)sensor.reset()sensor.set_framesize(width=W, height=H)sensor.set_pixformat(Sensor.RGB888)Display.init(Display.ST7701, width=640, height=480, to_ide=True)sensor.run()time.sleep(0.5)Create Template and Threshold
xxxxxxxxxxTS = 20templ = np.zeros((TS, TS, 1), dtype=np.uint8)cv2.rectangle(templ, (8, 8), (TS - 8, TS - 8), (255,), -1)THR = 0.6The template outer frame size is 20×20, with a white area drawn from coordinates 8 to 12. The "40×40 white square template" in the source code comments refers to the template outer frame description after mapping to the original image, not that the template array itself is 40×40.
Downsample and Binarize
xxxxxxxxxxsmall = cv2.resize(img_np, (320, 240))gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)ret, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)The fixed threshold of 200 only keeps brighter regions, making the search image data format consistent with the black background white block template.
Match and Find Best Position
xxxxxxxxxxresponse = cv2.matchTemplate( binary, templ, cv2.TM_CCOEFF_NORMED)min_value, max_value, min_location, max_location = cv2.minMaxLoc(response)max_value is the best score, and max_location is the coordinates of the template's top-left corner in the 320×240 search image.
Draw Match Box
xxxxxxxxxxif max_value > THR: x = max_location[0] * 2 y = max_location[1] * 2 cv2.rectangle( img_np, (x, y), (x + TS * 2, y + TS * 2), (0, 255, 0), 2 )Both template size and position are multiplied by 2 to map the 320×240 match result to the 640×480 image.
Print Score and Release Resources
xif time.ticks_diff(time.ticks_ms(), ft) >= 1000: print("match best:{:.2f} | fps:{}".format(max_value, fc))
finally: sensor.stop() Display.deinit() os.exitpoint(os.EXITPOINT_ENABLE_SLEEP) time.sleep_ms(100)Parameter Adjustment Notes
Template Content: The template should come from real targets processed through the same preprocessing pipeline. A fixed hand-drawn template is only suitable for API demonstration.
Threshold 200: Lower it when the target is not bright enough; raise it when background bright areas cause false detections. The template and search image must use consistent binarization rules.
Confidence THR=0.6: Raise it when false detections are high; lower it when missed detections are high. Determine a reasonable range through positive and negative sample statistics.
Scale Variation: When target size varies, a single template can easily fail. Prepare multiple scale templates or search within a limited scale range.
Rotation Variation: Template matching does not have rotation invariance inherently. You need to prepare rotated templates or switch to feature-based methods.
Search Region: Limiting ROI can significantly reduce computation and background false detections, making it the preferred optimization for embedded real-time applications.
Template Size: The template must not be larger than the search image; otherwise, the function cannot produce a valid response map.