gpt4 book ai didi

java - 需要使用矩阵平滑图像 - 计算单元格总和并计算平均值

转载 作者:行者123 更新时间:2023-12-02 10:01:42 25 4
gpt4 key购买 nike

我有矩阵,每个单元格包含我需要计算该单元格及其相邻单元格的数字,并得出该单元格的平均值。

看看我写的代码。

public Matrix imageFilterAverage() {
for (int i=0; i < _array.length;i++)
for (int j=0; i < _array[i].length;j++){
_array[i][j] = (_array[i][j] + _array[i][j+1] + _array[i+1][j] + _array[i+1][j+1]) / 4;
}

return this;
}

当 j+1 达到 3 时,我的代码在索引问题上返回错误,它超出范围,因为单元格为 0 1 2。

例如,如果我有一个像这样的矩阵

10 5 7 3
50 3 2 1
60 2 5 2

结果矩阵应该是这样的。

17 12 3 3
21 16 2 3
28 20 2 2

我已经发布了图像一个矩阵源和矩阵结果 source matrix

Results matrix

非常感谢您的时间和帮助。

最佳答案

    /**
* Takes the given array and transforms each slot in the array as an average of the slots around it.
* @return an array with each where each slot in the array is "blurred" by the slots around it.
*/
public Matrix imageFilterAverage() {
int avgArray[][] = new int[_twoDiPicture.length][];
int numOfCellsAround = 0;
int cellsSum = 0;
for (int y = 0; y < _twoDiPicture.length; y++) {
avgArray[y] = new int[_twoDiPicture[y].length];
for (int x = 0; x < _twoDiPicture[y].length; x++) {
numOfCellsAround = 0;
cellsSum = 0;
numOfCellsAround += cellsAround(y, x);
cellsSum += cellsSum(y, x);
avgArray[y][x] = cellsSum / numOfCellsAround;
}
}

return new Matrix(avgArray);
}

/* a private method that deals with index out of bound exceptions. */
private boolean isInBounds(int y, int x) {
return y < _twoDiPicture.length && y >= 0 && x < _twoDiPicture[y].length && x >= 0;
}

/* A private methods that uses "isInBounds" to find how many cells are surrounding the target array. */
private int cellsAround(int y, int x) {
int cells = 1;

if (isInBounds(y + 1, x)) {
cells++;
}
if (isInBounds(y - 1, x)) {
cells++;
}
if (isInBounds(y, x + 1)) {
cells++;
}
if (isInBounds(y, x - 1)) {
cells++;
}
if (isInBounds(y - 1, x + 1)) {
cells++;
}
if (isInBounds(y - 1, x - 1)) {
cells++;
}
if (isInBounds(y + 1, x - 1)) {
cells++;
}
if (isInBounds(y + 1, x + 1)) {
cells++;
}

return cells;
}


/*A private method that returns the sum of all the adjacent cells around target cell. */
private int cellsSum(int y, int x) {
int sum = _twoDiPicture[y][x];

if (isInBounds(y + 1, x)) {
sum += _twoDiPicture[y + 1][x];
}
if (isInBounds(y - 1, x)) {
sum += _twoDiPicture[y - 1][x];
}
if (isInBounds(y, x + 1)) {
sum += _twoDiPicture[y][x + 1];
}
if (isInBounds(y, x - 1)) {
sum += _twoDiPicture[y][x - 1];
}
if (isInBounds(y - 1, x + 1)) {
sum += _twoDiPicture[y - 1][x + 1];
}
if (isInBounds(y - 1, x - 1)) {
sum += _twoDiPicture[y - 1][x - 1];
}
if (isInBounds(y + 1, x - 1)) {
sum += _twoDiPicture[y + 1][x - 1];
}
if (isInBounds(y + 1, x + 1)) {
sum += _twoDiPicture[y + 1][x + 1];
}

return sum;
}

关于java - 需要使用矩阵平滑图像 - 计算单元格总和并计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55576451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com