阿尔法修剪过滤器故障



我正在尝试在openCV库中制作一个按字母排列的过滤器。我的代码不能正常工作,所产生的图像不像过滤后的图像。过滤器的工作方式如下:

  1. 在我的例子中选择一些(数组)像素,它是9像素的'3x3'窗口。
  2. 按递增顺序排序
  3. 为alpha-2裁剪我们的'数组'。
  4. 计算剩余像素的算术平均值,并将其插入适当的位置。

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;
}

在没有实际数据的情况下,这是一种猜测,但uchar不能容纳3个通道的总和。它以256模工作(至少在OpenCV支持的任何平台上)。

适当的解决方案是std::sortVec3b的适当比较器:

void L1(Vec3b a, Vec3b b) { return a[0]+a[1]+a[2] < b[0]+b[1]+b[2]; }

最新更新