corr2 in matlab returns NaN

13 views (last 30 days)
Pranay Wankhede
Pranay Wankhede on 30 Oct 2016
Commented: Image Analyst on 30 Oct 2016
I am trying to use corr2 for template matching. But when I give the window around first pixel and template matrix to the function, I get NaN error.
For ex :
template = uint8([1 1 1 0; 1 1 1 0;1 1 1 0]);
window = uint8([0 0 0 0; 0 0 0 0;0 0 0 0]);
When i do corr2 on this two matrix :-
r = corr2(template,window);
r = NaN.
But if I change one of the zero value in matrix to 1 in window, it give me output other than NaN. I am following the link : https://www.youtube.com/watch?v=Q-OzmDen4HU for template matching which show output as 0 for the first pixel. I am not getting where I am doing wrong.

Answers (1)

Image Analyst
Image Analyst on 30 Oct 2016
It's a common misconception that correlation is for template matching. I hope when you think about it you'll realize why. You can easily think of counter examples where it won't find the pattern.
One weird thing is that your second matrix is all zeros so you'll have a zero in the denominator for the definition:
Your B and Bbar are all zero! So r = 0/0 which is undefined, or NaN.
See my attached template matching demo where I use normxcorr2().
  2 Comments
Pranay Wankhede
Pranay Wankhede on 30 Oct 2016
I can't use in built normxcorr2() function in matlab. Can you please tell me a user defined function as a replacement for built in ?
Image Analyst
Image Analyst on 30 Oct 2016
I have not written my own versions of the built-in functions. I have no need to. Why would I? If you want to rewrite any built-in functions, be my guest. http://www.mathworks.com/matlabcentral/answers/38787-what-can-be-programmed-without-any-built-in-functions

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!