我的问题并不是指我需要用什么操作符来操作矩阵,而是通过执行这个程序来实际寻找什么。如何正确地应用滤镜到图像数组?
例如,我有一个矩阵形式的图像,我需要执行几个操作(这个过滤器就是其中之一)。将所述图像转换为灰度后,我需要应用以下滤镜
float[][] smoothKernel = {
{0.1f,0.1f,0.1f},
{0.1f,0.2f,0.1f},
{0.1f,0.1f,0.1f}
};
就可以了。
作业文件给出了这个例子,所以我假设当被要求“平滑”图像时,我不得不用每个像素替换其邻居的平均值(同时还要确保特殊情况如角落或边被妥善处理)。
的基本思路是这样的:
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;
,从而避免覆盖输出的原始(图像的值是在这种情况下,所有的白色...)。从上面链接的示例中的最终产品,我无法理解发生了什么。
应用过滤器的正确方法是什么?这是一种通用的方法,还是因不同的过滤器而异?
感谢您花时间澄清此问题。
编辑:我发现了两个错误,我在下面的评论中详细说明,执行回代码,现在一切工作正常。
我也已经能够验证示例中的某些值计算错误(从而导致我的困惑),所以我一定会在下一节课中指出它。
创建一个新的数组似乎对我来说是正确的。我也会这样做。你有什么问题? – markspace
@markspace我得到一个白色的图像,当它应该输出一个模糊的灰度图像 –
@markspace我刚才意识到我必须在每个'smooth [col] [row]'之后设置'current = 0.0f',但是图像现在全灰了 –