import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
public class Voronoi
{
public static void main(String args[])
{
Random r = new Random();
BufferedImage buf = new BufferedImage(500, 500, BufferedImage.TYPE_3BYTE_BGR);
Point[] points = new Point[50];
for(int i = 0; i < points.length; i++)
{
points[i] = new Point(r.nextInt(500), r.nextInt(500));
}
int b = Color.BLUE.getRGB();
int w = Color.WHITE.getRGB();
int g = Color.GREEN.getRGB();
for(int i = 0; i < points.length; i++)
{
buf.setRGB(points[i].x, points[i].y, b);
}
ArrayList<Point> dis = new ArrayList<Point>();
int min = 5000;
for(int i = 0; i < buf.getWidth(); i++)
{
for(int j = 0; j < buf.getHeight(); j++)
{
for(int k = 0; k < points.length; k++)
{
if(buf.getRGB(i, j) == b)
continue;
int d = distance(i, points[k].x, j, points[k].y);
if(d == min)
{
dis.add(points[k]);
}
else if(d < min)
{
dis.clear();
dis.add(points[k]);
min = d;
}
}
if(dis.size() == 1)
{
buf.setRGB(i, j, w);
}
else if(dis.size() > 1)
{
Point m = midPoint(dis);
buf.setRGB(m.x, m.y, g);
}
dis.clear();
min = 5000;
}
}
try
{
ImageIO.write(buf, "png", new File("this.png"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int distance(int x1, int y1, int x2, int y2)
{
return (int)Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
public static Point midPoint(ArrayList<Point> p)
{
int totX = 0;
int totY = 0;
for(Point a: p)
{
totX += a.x;
totY += a.y;
}
totX /= p.size();
totY /= p.size();
return new Point(totX, totY);
}
}
它生成的所有内容都是这样的:
代码应该做什么: 逐个浏览每个像素,找到最接近每个像素的点[蓝点]。如果只有一个点,那个像素为白色。但是如果有多个点,则颜色为绿色。
答案 0 :(得分:0)
这是错误的:
最初:
int d = distance(i, points[k].x, j, points[k].y);
正确的版本:
int d = distance(i, j, points[k].x, points[k].y);
除此之外,我不应该像我在这里那样平均正确的分数:
Point m = midPoint(dis);
我应该只用颜色(i,j)绿色。