Problem with alpha-trimmed filter

asked 2016-10-18 14:10:52 -0600

Linnot gravatar image

I am trying to make an alphatrimmed filter in openCV library. My code is not working properly and the resultant image is not looking as image after filtering. The filter should work in the following way. Can you propose some modifications for my code?

1.Chossing some (array) of pixels in my example it is 9 pixels '3x3' window.

2.Ordering them in increasing way.

3.Cutting our 'array' both sides for alpha-2.

4.calculating arithmetic mean of remaining pixels and inserting them in proper place.

int alphatrimmed(Mat img, int alpha)
{
Mat img9 = img.clone();
const int start = alpha/2 ;
const int end = 9 - (alpha/2);

//going through whole image
for (int i = 1; i < img.rows - 1; i++)
{
for (int j = 1; j < img.cols - 1; j++)
{
uchar element[9];
Vec3b element3[9];
int k = 0;
int a = 0;
//selecting elements for window 3x3
    for (int m = i -1; m < i + 2; m++)
    {
        for (int n = j - 1; n < j + 2; n++)
        {
            element3[a] = img.at<Vec3b>(m*img.cols + n);
            a++;
                for (int c = 0; c < img.channels(); c++)
                {
                    element[k] += img.at<Vec3b>(m*img.cols + n)[c];
            }
                k++;
        }
    }
//comparing and sorting elements in window (uchar element [9])
for (int b = 0; b < end; b++)
{
    int min = b;
    for (int d = b + 1; d < 9; d++)
    {
        if (element[d] < element[min])
        {
            min = d;
            const   uchar temp = element[b];
            element[b] = element[min];
            element[min] = temp;
            const   Vec3b temporary = element3[b];
            element3[b] = element3[min];
            element3[min] = temporary;
        }
    }

}

//  index in resultant image( after alpha-trimmed filter)
int result = (i - 1) * (img.cols - 2) + j - 1;
for (int l = start ; l < end; l++)
    img9.at<Vec3b>(result) += element3[l];
img9.at<Vec3b>(result) /= (9 - alpha);
}
}
namedWindow("AlphaTrimmed Filter", WINDOW_AUTOSIZE);
imshow("AlphaTrimmed Filter", img9);
return 0;
}

Thank you for your help.

edit retag flag offensive close merge delete

Comments

can you try to explain the idea behind your filter a bit better ? then we can try to find a better way coding it (definitely not like you try now, please try to avoid any per-pixel loops)

berak gravatar imageberak ( 2016-10-18 15:33:12 -0600 )edit

The main idea is to go through the whole image, choosing a square 3x3 or 4x4. After that putting chosen elemnts in an container, and sorting them. Later we are cutting from boh sides (alpha/2)elements and we obtained sorted container downsized for alpha elements. From elements which, are not deleted we calculate arithmetic mean and put this value to the window which we have chosen.

Linnot gravatar imageLinnot ( 2016-10-18 16:52:45 -0600 )edit