1

我正在使用位图图像在 Java 中实现中值滤波器。我正在使用以另一种编程语言实现的算法,然后将其转换为 Java 用于我的实现。我不明白的算法部分如下:

for(int x = 0; x < w; x++) 
for(int y = 0; y < h; y++) 
{ 
    int n = 0;
    //set the color values in the arrays
    for(int filterX = 0; filterX < filterWidth; filterX++)
    for(int filterY = 0; filterY < filterHeight; filterY++)
    {
        int imageX = (x - filterWidth / 2 + filterX + w) % w;
        int imageY = (y - filterHeight / 2 + filterY + h) % h;
        red[n] = image[imageX][imageY].r;
        green[n] = image[imageX][imageY].g;
        blue[n] = image[imageX][imageY].b;
        n++;
    }        

这是中值算法的链接

我自己实现了以下代码,但我认为它不正确。如果有人可以帮助我,我将不胜感激。

for(int x = 0; x < width; x++)
    {
        for(int y = 0; y < height; y++) 
        { 
            int n = 0;
            for(int filterX = 0; filterX < filterWidth; filterX++)

                for(int filterY = 0; filterY < filterHeight; filterY++)
                {

                    pixel = image.getPixel(x,y);  
                    A = (pixel>>24) & 0xFF;
                    R = (pixel>>16) & 0xFF;
                    G = (pixel>>8) & 0xFF;
                    B = pixel & 0xFF;

                    RArray[n] = R;
                    GArray[n] = G;
                    BArray[n] = B;
                    n++;

            }        
4

2 回答 2

3

您需要分析 N 个像素并找到中间值以获得中值。
您需要使用不断变化的 filterX 和 filterY 值作为偏移量来获取除 x 和 y 之外的其他像素。

getPixel(x+filterX,y+filterY)

于 2013-07-26T02:01:21.807 回答
3

我看不到您在哪里选择输入值的中位数。正如吉姆所提到的,一定要处理边缘情况,例如......

for(int x = 0; x < width; x++)
{
    for(int y = 0; y < height; y++) 
    { 
        int index = 0;
        for(int filterX = -filterWidth/2; filterX < filterWidth/2; filterX++)
            for(int filterY = -filterHeight/2; 
                 filterY < filterHeight/2; filterY++)
        {
            int pixelX = x+filterX;
            int pixelY = y+filterY;

            //ensure we're in bounds.
            if(pixelX>-1 && pixelY>-1 && pixelX<w && pixelY<h){
                pixel = image.getPixel(x,y);
                A = (pixel>>24) & 0xFF;
                R = (pixel>>16) & 0xFF;
                G = (pixel>>8) & 0xFF;
                B = pixel & 0xFF;

                RArray[index] = R;
                GArray[index] = G;
                BArray[index] = B;
                ++index;
        }
   }
   //only sort the pieces of the array we've put data into,
   //remember we could be on an edge of the image.
   Arrays.sort(RArray,0,index);
   Arrays.sort(BArray,0,index);
   Arrays.sort(GArray,0,index);
   int medianR = RArray[RArray.length/2];
   int medianB = BArray[BArray.length/2];
   int medianG = GArray[GArray.length/2];

   //last step is to combine medians back into a single integer
于 2013-07-26T02:04:01.780 回答