我正在尝试使用渐变公式计算像素的能量,但我遇到问题时出于某种原因,除了图像边缘以外的所有内容都会计算出来。例如
从命令行读取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;
}
答案 0 :(得分:0)
问题在于您的代码中的这种情况:
// border case
if (x == 0 || y == 0 || x == (width() - 1) || y == (height() - 1)) {
return 3 * 255 * 255;
}
这最终会为所有边缘点返回195075
。
我不知道您使用什么公式来获得所需答案中的边缘点能量,但您应该在代码中使用相同的公式,而不是仅返回195075
。