How can I imitate medfilt2 of Matlab with OpenCV?

2020-06-23 07:29发布

问题:

I have an imaging application written in Matlab and need to convert it into C++ app with OpenCV. But I can't seem to find an easy way to imitate medfilt2 with OpenCV.

I tried MedianBlur but it didn't produce the same result. Could anybody give me any clue for this task?

回答1:

It would appear to me that this link should have what you need. However, looks like you'll have to make a minor modification if you want to specify the n by m window.

     //   Pick up window elements
     int k = 0;
     // Original: element window[9];
     element window[n_win*m_win];
     for (int j = m_win - 1; j < m_win; ++j)
        for (int i = n_win - 1; i < n_win; ++i)
           window[k++] = image[j * N + i];
     //   Order elements (only half of them)
     // make sure (n_win*m_win)/2 is odd :-)
     for (int j = 0; j < (n_win*m_win)/2; ++j)
     {
        //   Find position of minimum element
        int min = j;
        for (int l = j + 1; l < n_win*m_win; ++l)
        if (window[l] < window[min])
           min = l;
        //   Put found minimum element in its place
        const element temp = window[j];
        window[j] = window[min];
        window[min] = temp;
     }
     //   Get result - the middle element
     result[(m - 1) * (N - 2) + n - 1] = window[4];