Here is a minimal example of what i try to do:
Create 3D matrix
a(:,:,1)=[
1 2 3 4 1;
2 3 7 1 4;
3 7 6 0 9;
0 3 2 8 1;
1 4 3 1 1]
a(:,:,2)=[
1 7 3 4 2;
2 9 2 3 1;
1 4 7 7 0;
1 2 3 4 1;
0 9 3 3 9]
a(:,:,3)=[
9 4 0 3 5;
1 2 3 4 1;
2 0 2 3 1;
1 4 2 1 1;
2 5 7 8 1]
a(:,:,4)=[
2 3 5 2 0
0 0 0 0 8
5 2 7 9 8
2 4 1 1 0
6 3 8 7 9]
a(:,:,5)=[
3 5 1 4 6;
3 2 8 0 0;
0 2 1 0 4;
5 4 5 5 6;
9 5 9 9 5]
Create 3D template
b(:,:,1)=[
9 4 0;
1 2 3;
2 0 2]
b(:,:,2)=[
2 3 5;
0 0 0;
5 2 7]
b(:,:,3)=[
3 5 1;
3 2 8;
0 2 1]
Calculate Cross Correlation (3D cross-correlation in matlab). I think Cross Correlation is the same as convolution with the flipped template. Is that correct?
c=convn(a,b(end:-1:1,end:-1:1,end:-1:1));
Find subscripts of best matching
[x y z] = ind2sub(size(c),find(c==max(c(:))));
x=x-(size(b, 1) - 1)/2
y=y-(size(b, 2) - 1)/2
z=z-(size(b, 3) - 1)/2
I read that one has to subtract the half of the template size of the final coordinates but I don't have the link of the page with this information anymore. However, I think if one wouldn't do that returned coordinates are not the one of where the center of the template would be but on a corner of the template.
As result of my example I expect: x=2
, y=2
, z=4
. Matlab tells me it's x=4
, y=4
, z=4
. However, when changing the template to
b(:,:,1)=[
9 2 3;
4 7 7;
2 3 4]
b(:,:,2)=[
2 3 4;
0 2 3;
4 2 1]
b(:,:,3)=[
0 0 0;
2 7 9;
4 1 1]
I get the correct result (x=3, y=3, z=3)
.
What do I have to change to get always the correct result?