I am trying to convert some OpenCV code I wrote to Matlab and ran into some problems with filter2D. I do not think I fully understand how filter2D works. I tried implementing the function using the equation given in the docs:
I think I must be missing something though because my Matlab code result does not match the filter2D result :( For input mat = [1 2 3; 4 5 6; 7 8 9] and kernel = [1 1 1; 1 1 1; 1 1 1], I get in Matlab result mat = [21, 27, 33; 39, 45, 51; 57, 63, 69] and in OpenCV result mat = [34, 37, 40; 43, 46, 49; 52, 55, 58]
For OpenCV I use filter2D(src, dst, -1, ker, Point(-1,-1), BORDER_REPLICATE)
Here is my Matlab code (I assume BORDER_REPLICATE (Matlab is missing a corresponding BORDER_REFLECT and (more importantly) BORDER_REFLECT_101 padding) and default anchor):
% X - input image
% kernel - convolution kernel (or rather a correlation kernel), a single-channel floating point matrix
% anchor - anchor of the kernel that indicates the relative position of a filtered point within the kernel; the anchor should lie within the kernel
function Y = filter_2D(X, kernel)
[k_rows, k_cols] = size(kernel);
[x_rows, x_cols] = size(X);
Y = zeros(x_rows, x_cols);
% Assume padding used in OpenCV is BORDER_REPLICATE aaaaaa|abcdefgh|hhhhhhh
X_pad = padarray(X, [floor(k_rows/2) floor(k_cols/2)], 'replicate', 'both');
for r = 1:k_rows
for c = 1:k_cols
Y(r,c) = sum(sum(kernel .* X_pad(r:r+k_rows-1, c:c+k_cols-1)));
end
end
end
Can someone point out what I am doing wrong/need to change? Thanks!