# Calculation of TM_CCOEFF_NORMED for template matching

This template image below gives always 1.0: best matching result in every source image. @pklab said here it is because the formula of TM_CCOEFF_NORMED returns 0/0 because the template image is constant color and opencv returns 1.0 to avoid match exception, but I still don't get it. I would understand better with an example, lets say template image = 3x4 pixels and source image = 10x12 pixels, could someone put the values in the formula please and show 0/0?

edit retag close merge delete

Why would you matching the template of a single colour? isn't it better to do segmentation and detect the biggest square in that region?

@thdrksdfthmn I don't have a choice, it must be this way for now, I just want to understand the formula...

Sort by » oldest newest most voted As I said

At this time this is an open bug.

The issue highlighting should be clear to understand: here is the formula:

J = I(x,y) - AVG(I)   //I: the image portion under template
U = T(x,y) - AVG(T)   //T: the template
TM_CCOEFF_NORMED = SUM(U * J) / sqrt(SUM(U^2) * SUM(J^2))


In case of constant template each pixel is same as the average than:

U = T(x,y) - AVG(T) = 0
TM_CCOEFF_NORMED = SUM(0 * J) / sqrt[ SUM(0^2) * SUM(J^2) ] = 0/0


This is same also if the image portion under template is constant (J=0)

If you don't trust, try yourself with numbers

more

@pklab Thanks it is clear but I dont see where "J = I(x,y) - AVG(I)" comes from, where does it say on the documentation or formula we have to subtract AVG(I) or AVG(U) to get U,J?

Look at formula: T' is U in my answer. Is sum(T)/(w*h) = AVG(T) ?

Official site

GitHub

Wiki

Documentation