迭代2D数组并获得相邻单元格的平均值

时间:2015-10-27 05:28:33

标签: java

我要做的是遍历2D array以找到average

middle中的值必须计算为4边(Top,Bottom,Left,Right and recalculated)的平均值。我必须找到当前索引的四边的值,并用该数字替换当前索引。任何想法都将不胜感激。

final public class Matrix {
private final int M;             // number of rows
private final int N;             // number of columns
private final double[][] data;   // M-by-N array

// create M-by-N matrix of 0's
public Matrix(int M, int N) {
    this.M = M;
    this.N = N;
    data = new double[M][N];
}

// create matrix based on 2d array
public Matrix(double[][] data) {
    M = data.length;
    N = data[0].length;
    this.data = new double[M][N];
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
                this.data[i][j] = data[i][j];
}

// copy constructor
private Matrix(Matrix A) { this(A.data); }



// print matrix to standard output
public void show() {
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) 
            System.out.printf("%.1f ", data[i][j]);
        System.out.println();
    }
}



// test client
public static void main(String[] args) {
    double[][] d = { { 22.5,30,30,30,30,30,30,30,30,51 }, 
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 15,0,0,0,0,0,0,0,0,72 },
                     { 45,75,75,75,75,75,75,75,75,73.5 }

    };


    Matrix D = new Matrix(d);
    D.show(); 
    System.out.println();



}
}

1 个答案:

答案 0 :(得分:0)

您所描述的只是一种非常简单的模糊操作,基本上是box blur的一种形式。对图像中的每个像素采用NxN子矩阵并将其乘以另一个NxN矩阵的任何操作称为kernel convolution。 Rosetta Code在this page上的Java中有一个很好的例子。

如果您可以使用AWT,则Java标准库已内置ConvolveOp