使用Java(最小过滤器)进行图像处理;将元素放置在 2D 矩阵的中心



我正在尝试使用java在".pgm"文件上实现各种图像处理过滤器。下面是最小过滤器的代码:

void applyMinFilter() {
int [] array = new int[size*size];
int t = 0, i = 0, j = 0;
for(int c = 0; c<h-size+1; c++) {
for(int k = 0; k<w-size+1; k++) {
t = 0;
for(i = c; i<c+size; i++) { 
for(j = k; j<k+size; j++) {
array[t++] = matrix[i][j];
}
}
//placing the minimum value in the centre of the considered grid
matrix[i/2][j/2] = minimum(array);
}
}
}

注意:这里,大小 = 5,w = h = 400

使用这种方法,我得到一个输出,其中我想要的图像位于照片的一角。您可以通过单击此处查看输出图像。在我的代码中,c 循环和 k 循环帮助我们遍历整个图像,而 i 循环和 j 循环为我们提供了应用最小过滤器所需的小窗口。我已经将".pgm"图像转换为用于操作的矩阵。

我很确定错误来自评论行之后的行。我无法将最小值像素正确放置在正确的位置。我该怎么办?

你应该用matrix[c+size/2][k+size/2]替换matrix[i/2][j/2]的索引,或者你可以做如下代码:

void applyMinFilter() {
int [] array = new int[size*size];
int t = 0, i = 0, j = 0;
// for size = 5 you can use h-2 or w-2
// to make it general replace with h-size/2 and w-size/2
for(int c = 2; c < h-2; c++) {
for(int k = 2; k < w-2; k++) {
t = 0;
for(i = c-2; i < c+2; i++) { 
for(j = k-2; j < k+2; j++) {
array[t++] = matrix[i][j];
}
}
//placing the minimum value in the centre of the considered grid
matrix[c][k] = minimum(array);
}
}
}

最新更新