The following is my attempt to calculate the cross-correlation of two images manually. Something is not quite right. Look at it again this weekend if I have time. You can call the function with something like:
>> oldImage = rand (64);
>> newImage = circshift (oldImage, floor (64/2) * [1 1]);
>> offset = detectOffset (oldImage, newImage, 10)
offset =
32 -1
function offset = detectOffset(oldImage, newImage, margin) if size(oldImage) ~= size(newImage) offset = []; error('Test images must be the same size.'); end [imageHeight, imageWidth] = size(oldImage); corr = zeros(2 * imageHeight - 1, 2 * imageWidth - 1); for yIndex = [1:2*imageHeight-1; ... imageHeight:-1:1 ones(1, imageHeight-1); ... imageHeight*ones(1, imageHeight) imageHeight-1:-1:1]; oldImage = circshift(oldImage, [1 0]); for xIndex = [1:2*imageWidth-1; ... imageWidth:-1:1 ones(1, imageWidth-1); ... imageWidth*ones(1, imageWidth) imageWidth-1:-1:1]; oldImage = circshift(oldImage, [0 1]); numPoint = abs(yIndex(3) - yIndex(2) + 1) * abs(xIndex(3) - xIndex(2) + 1); corr(yIndex(1),xIndex(1)) = sum(sum(oldImage(yIndex(2):yIndex(3),xIndex(2):xIndex(3)) .* newImage(yIndex(2):yIndex(3),xIndex(2):xIndex(3)))) * imageHeight * imageWidth / numPoint; end end [value, yOffset] = max(corr(margin+1:end-margin,margin+1:end-margin)); [dummy, xOffset] = max(value); offset = [yOffset(xOffset)+margin-imageHeight xOffset+margin-imageWidth];
source share