我需要用某种颜色(例如红色)填充此灰度图片。我考虑使用Flood Fill算法,因为我需要在某些特定位置进行填充。
我找到了这种方法,但是由于图片线条的反锯齿,结果有些难看的白色部分。
在我的代码中:
颜色targetColor =白色,
颜色替换颜色=红色。
我认为我需要将替代品更改为更多的灰色,而不仅仅是白色。
我应该坚持使用这种方法并进行一些更改吗?还是找到其他东西?
如果是,该更改什么?
我也尝试过此链接,但是不起作用:
noblemaster.com/public/download/FloodFill.java.html
图片链接:
image without red color
image with filled red color
public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) {
int width = image.getWidth();
int height = image.getHeight();
int target = targetColor.getRGB();
int replacement = replacementColor.getRGB();
if (target != replacement) {
Deque<Point> queue = new LinkedList<Point>();
do {
int x = node.x;
int y = node.y;
while (x > 0 && image.getRGB(x - 1, y) == target) {
x--;
}
boolean spanUp = false;
boolean spanDown = false;
while (x < width && image.getRGB(x, y) == target) {
image.setRGB(x, y, replacement);
if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
queue.add(new Point(x, y - 1));
spanUp = true;
} else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) {
spanUp = false;
}
if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) {
queue.add(new Point(x, y + 1));
spanDown = true;
} else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) {
spanDown = false;
}
x++;
}
} while ((node = queue.pollFirst()) != null);
}
}
最佳答案
这就是我最后所做的,最后的图片是this。
distanceOfColor是一个参数,在我的情况下,该数字要比清除所有灰色抗锯齿的数字多300-400。
public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) {
int width = image.getWidth();
int height = image.getHeight();
int target = targetColor.getRGB();
int replacement = replacementColor.getRGB();
int distanceOfColor=320;
if (target != replacement) {
Deque<Point> queue = new LinkedList<Point>();
do {
int x = node.x;
int y = node.y;
while (x > 0 && ColorDistance(image.getRGB(x - 1, y), target)<=distanceOfColor) {
x--;
}
boolean spanUp = false;
boolean spanDown = false;
while (x < width && ColorDistance(image.getRGB(x, y), target) <=distanceOfColor) {
image.setRGB(x, y, replacement);
if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
queue.add(new Point(x, y - 1));
spanUp = true;
} else if (spanUp && y > 0 && ColorDistance(image.getRGB(x, y - 1), target) >distanceOfColor) {
spanUp = false;
}
if (!spanDown && y < height - 1 && ColorDistance(image.getRGB(x, y + 1), target) <=distanceOfColor) {
queue.add(new Point(x, y + 1));
spanDown = true;
} else if (spanDown && y < height - 1 && ColorDistance(image.getRGB(x, y + 1), target) >distanceOfColor) {
spanDown = false;
}
x++;
}
} while ((node = queue.pollFirst()) != null);
}
}
关于java - 用于抗锯齿灰度图像Java的Flood Fill算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37168515/