我需要编写一个泛洪算法,用于给图像中黑色边框内的像素着色。我参考了一些 SO 上的帖子,编写了以下代码:
private Queue<Point> queue = new LinkedList<Point>();
private int pickedColorInt = 0;
private void floodFill(Pixmap pixmap, int x, int y){
//set to true for fields that have been checked
boolean[][] painted = new boolean[pixmap.getWidth()][pixmap.getHeight()];
//skip black pixels when coloring
int blackColor = Color.rgba8888(Color.BLACK);
queue.clear();
queue.add(new Point(x, y));
while(!queue.isEmpty()){
Point temp = queue.remove();
int temp_x = temp.getX();
int temp_y = temp.getY();
//only do stuff if point is within pixmap's bounds
if(temp_x >= 0 && temp_x < pixmap.getWidth() && temp_y >= 0 && temp_y < pixmap.getHeight()) {
//color of current point
int pixel = pixmap.getPixel(temp_x, temp_y);
if (!painted[temp_x][temp_y] && pixel != blackColor) {
painted[temp_x][temp_y] = true;
pixmap.drawPixel(temp_x, temp_y, pickedColorInt);
queue.add(new Point(temp_x + 1, temp_y));
queue.add(new Point(temp_x - 1, temp_y));
queue.add(new Point(temp_x, temp_y + 1));
queue.add(new Point(temp_x, temp_y - 1));
}
}
}
}
这并不像预期的那样工作。例如,在下面的测试图像上:
随机矩形将根据我点击的位置而重新着色。例如,单击紫色矩形下方的任何位置都会重新着色紫色矩形。在紫色矩形内部点击会重新着色绿色矩形。我已经检查过,并且将正确的参数传递给方法,因此问题可能出现在我的循环内部。
y = pixmap.getHeight() - y
来翻转y坐标。 - noone