different result of filter2D between c++ and python

asked 2020-03-19 05:42:42 -0600

TiTi243 gravatar image

I'm trying to do convolution in opencv from this but the results seems off

Opencv 4.2.0, Python 3.7

in C++ :

cv::Mat dst;
float K[5] = { -0.014, -0.45, 0, 0.45, 0.014 };
cv::Mat kernel(1, 5, CV_32F, K);
cv::Mat kernel_p(1, 5, CV_32F);
cv::flip(kernel, kernel_p, -1);

float test[6][6] = { {1, 2, 3, 4,5,6},{1, 2, 3, 4,5,6},{1, 2, 3, 4,5,6},{1, 2, 3, 4,5,6},{1, 2, 3, 4,5,6},{1, 2, 3, 4,5,6} };
cv::Mat myMat(6, 6, CV_32FC1, &test);

cv::filter2D(myMat, dst, -1, kernel_p, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);

result:

[-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306;
-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306;
-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306;
-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306;
-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306;
-0.94199997, -0.95599991, -0.95599997, -0.95600009, -0.8579998, 2.306]

but in python:

x = np.asarray([[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]],dtype=np.float32)
kernel = np.array([-0.014, -0.45, 0, 0.45, 0.014], dtype=np.float32)
print(cv2.filter2D(x, -1, cv2.flip(kernel, -1), anchor= (-1,-1), borderType=cv2.BORDER_CONSTANT))

result:

[[-0.464      -0.928      -1.392      -1.856      -2.32       -2.784     ]
[-0.014      -0.028      -0.042      -0.056      -0.07       -0.08400001]
[-0.         -0.          0.00000005 -0.00000001 -0.00000007  0.0000001 ]
[-0.         -0.          0.00000005 -0.00000001 -0.00000007  0.0000001 ]
[ 0.014       0.028       0.04200006  0.05599999  0.06999993  0.08400011]
[ 0.464       0.928       1.392       1.856       2.32        2.784     ]]

is this bug or there is something wrong in my code?

edit retag flag offensive close merge delete

Comments

No. You cannot used no.float32 and np.asarray

supra56 gravatar imagesupra56 ( 2020-03-19 09:59:23 -0600 )edit

@supra56 what do you mean? doesn't filter2d expecting floating-point number on src and kernel?

TiTi243 gravatar imageTiTi243 ( 2020-03-20 05:11:18 -0600 )edit

You can use np.float32 and use this np.array.

supra56 gravatar imagesupra56 ( 2020-03-21 07:54:26 -0600 )edit