如何正确地将滤镜应用于图像阵列?

时间:2015-10-26 18:29:47

标签: java matrix filter

我的问题并不是指我需要使用哪些运算符来操作矩阵,而是通过执行此过程实际寻求的是什么。

例如,我有一个矩阵形式的图像,我需要在其上执行几个操作(这个过滤器就是其中之一)。将所述图像转换为灰度后,我需要应用以下过滤器

float[][] smoothKernel = {
            {0.1f,0.1f,0.1f},
            {0.1f,0.2f,0.1f},
            {0.1f,0.1f,0.1f}
    };

就可以了。

赋值文件给出了这个例子this example,所以我假设当被要求“平滑”图像时,我不得不用其邻居的平均值替换每个像素(同时还要确保特殊情况,如角落或侧面处理得当。)

基本理念是:

public static float[][] filter(float[][] gray, float[][] kernel) {
    // gray is the image matrix, and kernel is the array I specifed above
    float current = 0.0f;
    float around = 0.0f;
    float[][] smooth = new float[gray.length][gray[0].length];
    for (int col = 0; col < gray.length; col++) {
        for (int row = 0; row < gray[0].length; row++) { 
        //first two for loops are used to do this procedure on every single pixel
        //the next two call upon the respective pixels around the one in question 
            for (int i = -1; i < 2; i++) {
                for (int j = -1; j < 2; j++) {
                    around = at(gray, i + col, j + row); //This calls a method which checks for the 
                                             //pixels around the one being modified
                    current += around * kernel[i+1][j+1]; 
                    //after the application of the filter these are then added to the new value
                }
            }
            smooth[col][row] = current; 
            current = 0.0f;
            //The new value is now set into the smooth matrix
        }
    }
    return smooth;
}

我的困境在于,如果我必须创建这个新数组float[][] smooth;,以避免覆盖原始值(在这种情况下输出的图像都是白色的......)。从我上面链接的示例中的最终产品,我无法理解发生了什么。

应用滤镜的正确方法是什么?这是一种通用方法还是针对不同的过滤器而有所不同?

感谢您抽出宝贵时间澄清这一点。

编辑:我在下面的评论中找到了两个错误,在代码中实现了,现在一切正常。

我还能够验证示例中的某些值是否计算错误(从而导致我的混淆),所以我一定会在下一课中指出它。

1 个答案:

答案 0 :(得分:0)

问题已经通过别有用心的方法解决了,但我没有删除它,希望其他人可以从中受益。原始代码可以在编辑中找到。

我的一位更高级的同事帮我注意到我错过了两件事:一个是在计算新数组中“平滑”变量后重置当前变量的问题(导致白色图像,因为这个值会变得越来越大,从而超过二进制颜色限制,所以它被设置为最大值)。第二个问题是我在同一个像素上不断迭代,这导致整个图像具有相同的颜色(我正在迭代新的数组)。所以我添加了这些规范,并且一切正常。

相关问题