计算机图形学扫描线种子填充算法java代码
时间: 2023-09-29 11:08:36 浏览: 132
扫描线种子填充算法步骤-计算机图形学ppt
以下是使用Java实现的扫描线种子填充算法:
```java
import java.awt.*;
import java.util.*;
public class ScanlineSeedFill {
private int[][] canvas; // 存储像素颜色的二维数组
private int width, height; // 画布宽度和高度
private int fillColor; // 填充的颜色
private int borderColor; // 边框颜色
private int tolerance; // 颜色容差
public ScanlineSeedFill(int[][] canvas, int width, int height, int fillColor, int borderColor, int tolerance) {
this.canvas = canvas;
this.width = width;
this.height = height;
this.fillColor = fillColor;
this.borderColor = borderColor;
this.tolerance = tolerance;
}
public void seedFill(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height) {
return; // 超出画布范围,返回
}
int targetColor = canvas[x][y]; // 目标颜色
if (targetColor == fillColor || targetColor == borderColor) {
return; // 已经填充过或者是边框颜色,返回
}
Queue<Point> queue = new LinkedList<>();
queue.offer(new Point(x, y));
while (!queue.isEmpty()) {
Point p = queue.poll();
int currentX = p.x;
int currentY = p.y;
if (currentX < 0 || currentX >= width || currentY < 0 || currentY >= height) {
continue;
}
int currentColor = canvas[currentX][currentY];
if (currentColor == targetColor || isSimilarColor(currentColor, targetColor)) {
canvas[currentX][currentY] = fillColor; // 填充当前像素
queue.offer(new Point(currentX + 1, currentY)); // 将下一列像素加入队列
queue.offer(new Point(currentX - 1, currentY)); // 将上一列像素加入队列
queue.offer(new Point(currentX, currentY + 1)); // 将下一行像素加入队列
queue.offer(new Point(currentX, currentY - 1)); // 将上一行像素加入队列
}
}
}
private boolean isSimilarColor(int color1, int color2) {
Color c1 = new Color(color1);
Color c2 = new Color(color2);
int diff = Math.abs(c1.getRed() - c2.getRed()) + Math.abs(c1.getGreen() - c2.getGreen()) + Math.abs(c1.getBlue() - c2.getBlue());
return diff <= tolerance;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
int[][] canvas = new int[][]{
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
};
int width = 7;
int height = 7;
int fillColor = 1;
int borderColor = 0;
int tolerance = 1;
ScanlineSeedFill fill = new ScanlineSeedFill(canvas, width, height, fillColor, borderColor, tolerance);
fill.seedFill(3, 3);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(canvas[i][j] + " ");
}
System.out.println();
}
}
}
```
输出结果:
```
0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 1 1 1 1 1 0
0 1 1 1 1 1 0
0 1 1 1 1 1 0
0 1 1 1 1 1 0
0 0 0 0 0 0 0
```
在这个例子中,我们创建了一个宽度和高度都为7的画布,并用0表示白色,1表示黑色。然后我们使用扫描线种子填充算法来填充从(3,3)开始的连通区域。填充颜色为1,边框颜色为0,颜色容差为1。最后输出填充后的画布。
阅读全文