我现在正在编写程序,我需要将当前像素与下面的像素进行比较,并在颜色距离大于边缘距离时将当前像素颜色设置为黑色。
代码:
public void edgeDetection(int edgeDist) {
Picture swan = new Picture("swan.jpg");
Pixel leftPixel = null;
Pixel rightPixel = null;
Pixel[][] pixels = this.getPixels2D();
Color rightColor = null;
Color botColor = null;
Pixel botPixel = null;
Pixel topPixel = null;
Color topColor = null;
for (int row = 1; row < pixels.length; row++) {
for (int col = 0; col < pixels[0].length - 1; col++) {
leftPixel = pixels[row][col];
rightPixel = pixels[row][col + 1];
rightColor = rightPixel.getColor();
for(int i = row + 1; i < pixels.length ; i++) {
topPixel = pixels[i][col];
botPixel = pixels[row][col];
botColor = botPixel.getColor();
topColor = topPixel.getColor();
if(topPixel.colorDistance(botColor) > edgeDist) {
topPixel.setColor(Color.BLACK);
}
else
leftPixel.setColor(Color.WHITE);
if (leftPixel.colorDistance(rightColor) > edgeDist) {
leftPixel.setColor(Color.GREEN);
}
else
leftPixel.setColor(Color.WHITE);
}
}
}
}
我最终弄清楚了。我删除了多余的循环,并重新整理了一些东西,它奏效了。代码:
public void edgeDetection(int edgeDist) {
Pixel leftPixel = null;
Pixel rightPixel = null;
Pixel[][] pixels = this.getPixels2D();
Color rightColor = null;
Color botColor = null;
Pixel botPixel = null;
Pixel topPixel = null;
for (int row = 0; row < pixels.length - 1 ; row++) {
for (int col = 0; col < pixels[0].length - 1; col++) {
leftPixel = pixels[row][col];
rightPixel = pixels[row][col + 1];
rightColor = rightPixel.getColor();
topPixel = pixels[row][col];
botPixel = pixels[row + 1][col];
botColor = botPixel.getColor();
if (leftPixel.colorDistance(rightColor) > edgeDist) {
leftPixel.setColor(Color.BLACK);
}
else if(topPixel.colorDistance(botColor) > edgeDist) {
topPixel.setColor(Color.BLACK);
}
else
topPixel.setColor(Color.WHITE);
}
}
}