Ask Your Question

Revision history [back]

Problem with alpha-trimmed filter

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.