E_learner
E_learner

Reputation: 3582

Equivalent function of Matlab's filter2 in OpenCV

I need to convert the following matlab code into OpenCV and obtain exactly the same result.

In matlab:

A = [1 2 3];
f = [4 5 6];
result = filter2(f, A);

This gives out as:

result = [17    32    23]

In OpenCV, I tried these lines:

cv::Mat A = (cv::Mat_<float>(1, 3) << 1, 2, 3);
cv::Mat f = (cv::Mat_<float>(1, 3) << 4, 5, 6);
cv::Mat result;
cv::filter2D(A, result, -1, f, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);

This gives me:

result = [21 32 41]

How can I obtain the same result as of Matlab?? I doubt the anchor point in OpenCV causes this difference, but I cannot figure out how to change it. Thanks in advance.

Upvotes: 1

Views: 1686

Answers (1)

beaker
beaker

Reputation: 16791

Use cv::BORDER_CONSTANT, which pads the array with zero rather than duplicating the neighboring element:

cv::filter2D(A, result, -1, f, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);

Result is:

result = [17, 32, 23]

Upvotes: 8

Related Questions