Java中的图形像素计数
好吧,经过整个下午的斗争,我似乎找不到正确的答案。 基本上,我有一个非常简单的设置,用白色背景填充我的画布,一个BuffereImage。然后,我从args数组中的点绘制一个多边形。显示方面,这是完美的作品。当我想计算多边形(已填充)使用的像素数时,问题就出现了
为此,我在画布上循环并使用getRGB方法比较每个像素,如果不是白色(背景色),则增加一个计数器。然而,我总是得到画布的尺寸(640*480),这意味着整个画布是白色的
所以我假设绘制到屏幕上的多边形没有添加到画布上,而是漂浮在顶部?这是我能想到的唯一答案,但可能是完全错误的
我想要的是能够计算非白色像素的数量。有什么建议吗
代码:
public class Application extends JPanel {
public static int[] xCoord = null;
public static int[] yCoord = null;
private static int xRef = 250;
private static int yRef = 250;
private static int xOld = 0;
private static int yOld = 0;
private static BufferedImage canvas;
private static Polygon poly;
public Application(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
fillCanvas(Color.WHITE);
poly = new Polygon(xCoord, yCoord, xCoord.length);
//Loop through each pixel
int count = 0;
for (int i = 0; i < canvas.getWidth(); i++)
for (int j = 0; j < canvas.getHeight(); j++) {
Color c = new Color(canvas.getRGB(i, j));
if (c.equals(Color.WHITE))
count++;
}
System.out.println(count);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(canvas, null, null);
g2.fillPolygon(poly);
}
public void fillCanvas(Color c) {
int color = c.getRGB();
for (int x = 0; x < canvas.getWidth(); x++) {
for (int y = 0; y < canvas.getHeight(); y++) {
canvas.setRGB(x, y, color);
}
}
repaint();
}
public static void main(String[] args) {
if (args != null)
findPoints(args);
JFrame window = new JFrame("Draw");
Application panel = new Application(640, 480);
window.add(panel);
Dimension SIZE = new Dimension(640, 480);
window.setPreferredSize(SIZE);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.pack();
}//end main
“findPoints(args)”方法太长,无法发布,但基本上它所做的一切都是获取参数值并编译点列表
提前感谢,, 靴子
# 1 楼答案
创建/填充画布时,您正在使用
BufferedImage
对象。poligon被捕获在Polygon
对象中。对屏幕的实际渲染是通过操纵Graphics
对象来完成的,因此在某种意义上,多边形是“浮动的”;也就是说:它不会显示在画布上,但在渲染图形对象时会绘制在画布上您将需要在画布上实际渲染多边形本身,或者从图形对象中获取像素并在其上执行计算
# 2 楼答案
只需添加一个感叹号即可反转条件中的布尔值:
更快的方法是检查rgb值,而不是首先为其创建颜色对象:
创建缓冲区图像,绘制多边形,然后计数。基本上,这是: