Tom*_*cic 6 java image-processing flood-fill libgdx
我需要编写一个泛光填充算法来为黑色边框内的图像的像素着色.我根据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));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不能按预期工作.例如,在以下测试图像上:
根据我点击的位置,随机矩形会变色.例如,单击紫色矩形下方的任何位置将重新着色紫色矩形.单击紫色矩形内部将重新着色绿色矩形.我已经检查了它,并且我将正确的参数传递给方法,所以问题可能在我的循环内部.
你的算法是正确的,只是你的输入参数不正确。
随机矩形将根据我单击的位置重新着色。例如,单击紫色矩形下方的任意位置将重新为紫色矩形着色。单击紫色矩形内部可重新为绿色矩形着色。
如果你看一下图片,彩色矩形并不是真正随机的。真正的问题是 Y 坐标不正确。具体来说,您的 Y 坐标是反转的。
这是因为大多数时候 LibGDX 使用左下、y 轴向上的坐标系,但也有使用Pixmap左上角 y 轴向下的坐标系。
解决此问题的一个简单方法是通过执行 来反转 Y 值y = pixmap.getHeight() - y。