Normalized Cross Correlation aka NCC is a basic pattern matching algorithm which effectively deal with very noise or blurring condition.
With a template image \(T\) and target image \(I\), matching equation is below.
\[s(u,v)=\frac{\sum_{x,y}(I(x,y)-\overline{I})(T(x -u, y-v) - \overline{T})}{\sqrt{\sum_{x,y}(I(x,y)-\overline{I})^2}\sqrt{\sum_{x,y}(T(x - u,y -v)-\overline{T})^2}}\tag{1}\]
For short, we can call \(I(x,y)\) as \(I\) and \(T(x-u, y-v)\) as \(T\)
The numerator is simplified as below
\[\sum(I-\overline I)(T - \overline T) = \sum I \cdot (T - \overline T) - \overline I \cdot \sum (T - \overline T) = \sum I \cdot (T - \overline T) = \sum I \cdot T - \frac{\sum I \sum T}{W \cdot H}\tag{2}\]
A part of the denominator \(\sum(I-\overline{I})^2\) can be expanded as below for later optimizing
\[\sum(I-\overline I)^2 = \sum I \cdot I - 2 \cdot \overline I \cdot \sum I + \sum \overline I \cdot \overline I = \sum I \cdot I - \frac{2 \cdot \sum I \cdot \sum I}{W \cdot H} + \frac{\sum I \cdot \sum I}{W \cdot H} = \sum I^2 - \frac{{(\sum I)}^2}{W \cdot H}\tag{3}\]
Similarly, \(\sum(T-\overline{T})^2\) is expanded as below
\[\sum(T-\overline{T})^2 = \sum T^2 - \frac{{(\sum T)}^2}{W \cdot H}\tag{4}\]
Substitute \(2\), \(3\) and \(4\) into \(1\), we get a new matching equation as below
\[s(u,v) = \frac{\sum I \cdot T - \frac{\sum I \sum T}{W \cdot H}}{\sqrt{\sum I^2 - \frac{{(\sum I)}^2}{W \cdot H}}\sqrt{\sum T^2 - \frac{{(\sum T)}^2}{W \cdot H}}}=\frac{\sum I \cdot T - \frac{\sum I \sum T}{W \cdot H}}{\frac{1}{W \cdot H}\sqrt{(W \cdot H \cdot \sum I^2 - (\sum I)^2) \cdot (W \cdot H \cdot \sum T^2 - (\sum T)^2)}}=\frac{W \cdot H \cdot \sum I \cdot T - \sum I \sum T}{\sqrt{(W \cdot H \cdot \sum I^2 - (\sum I)^2) \cdot (W \cdot H \cdot \sum T^2 - (\sum T)^2)}}\]
For the template \(T\), computation of \(\sum T\) and \(\sum T^2\) are done at initial step.
For the target image \(I\), \(\sum I^2\) and \(\sum I\) have to be computed at every sliding-window. However, it can be optimized more efficiently by using the Integral Image mechanism.