Search code examples
c++matlabopencveuclidean-distance

Substitute function of bwdist in C++


I am implementing a code of Matlab in C++. In Matlab they have used bwdist to calculate the euclidean distance.

I am using the function distanceTransform to get the same result as in Matlab, but the results are drastically different.

float tests[5][5] = {{0, 0, 0, 0,0},{0, 0, 0, 0,0},{0, 0, 1, 0,0},{0, 0, 0, 0,0},{0 , 0 , 0 , 0,0}};
    Mat test(5,5,CV_8UC1,&tests);
    Mat test_result = Mat::zeros(5,5,CV_32FC1);
    distanceTransform(test,test_result,CV_DIST_L1,3);

C++ Result is given below.

test_result = [0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]

All zeros while using in OpenCV. Whereas the Matlab Result is something different.

  2.8284    2.2361    2.0000    2.2361    2.8284
  2.2361    1.4142    1.0000    1.4142    2.2361
  2.0000    1.0000         0    1.0000    2.0000
  2.2361    1.4142    1.0000    1.4142    2.2361
  2.8284    2.2361    2.0000    2.2361    2.8284

Please suggest me some way to get the same result in C++/OpenCv too, as there is in Matlab.


Solution

  • I dare say the function works. Next time feed your matrices with proper data.

    uchar tests[5][5] = { //You create a 8UC1, so your data set type should match
        {1, 1, 1, 1, 1},
        {1, 1, 1, 1, 1},
        {1, 1, 0, 1, 1},
        {1, 1, 1, 1, 1},
        {1 ,1, 1, 1, 1}};
    Mat test(5, 5, CV_8UC1, tests); //tests is already a pointer
    Mat test_result;
    distanceTransform(test, test_result, CV_DIST_L2, 3); //You want euclidian distance