我正在尝试使用梯度公式计算像素的能量,但我遇到了问题,出于某种原因,除了图像边缘之外的所有内容都会计算。例如
,从命令行读取 6x5 图像,答案应如下所示:
57685 50893 91370 25418 33055 37246
15421 56334 22808 54796 11641 25496
12344 19236 52030 17708 44735 20663
17074 23678 30279 80663 37831 45595
32337 30796 4909 73334 40613 36556
但我得到
195075 195075 195075 195075 195075 195075
195075 56334 22808 54796 11641 195075
195075 19236 52030 17708 44735 195075
195075 23678 30279 80663 37831 195075
195075 195075 195075 195075 195075 195075
我的能量法
public double energy(int x, int y) {
if (x < 0 || x >= width()) {
throw new IndexOutOfBoundsException("x must be between 0 and " + (width()-1));
}
if (y < 0 || y >= height()) {
throw new IndexOutOfBoundsException("y must be between 0 and " + (height()-1));
}
// border case
if (x == 0 || y == 0 || x == (width() - 1) || y == (height() - 1)) {
return 3 * 255 * 255;
}
return Gradient(x, y);
}
public double Gradient(int x, int y) {
Color c1 = picture.get(x-1, y);
Color c2 = picture.get(x+1, y);
Color c3 = picture.get(x, y - 1);
Color c4 = picture.get(x, y + 1);
double deltaX = Math.pow(c2.getRed() - c1.getRed(), 2) +
Math.pow(c2.getBlue() - c1.getBlue(), 2) +
Math.pow(c2.getGreen() - c1.getGreen(), 2);
double deltaY = Math.pow(c4.getRed() - c3.getRed(), 2) +
Math.pow(c4.getBlue() - c3.getBlue(), 2) +
Math.pow(c4.getGreen() - c3.getGreen(), 2);
return deltaX + deltaY;
}