【问题标题】:Looping through image pixels is crashing my program循环通过图像像素使我的程序崩溃
【发布时间】:2014-06-08 23:04:11
【问题描述】:

我开始研究一个小图像处理软件。目前我只需要将图像设置为黑白并循环遍历其像素并生成每个像素(#,x,y,color)的计数器、坐标和颜色的报告。

它适用于我只是为了测试而创建的微小图像,但是当我使用真实图片时,它需要几分钟甚至使我的软件崩溃。我在循环中的代码似乎很容易崩溃。

关于如何改进它的任何提示?提前致谢!

void processImage(BufferedImage image) {
        exportStr = "#,x,y,color"+ newline;     

        Color c = new Color(0);
        int imgW = image.getWidth();
        int imgH = image.getHeight();
        matrix = new int[imgW][imgH]; 

        int currentPx = 1;

        for(int x=0; x < imgW; x++) 
        {
            for(int y=0; y < imgH; y++) 
            {
                c = new Color(image.getRGB(x, y));

                if(c.equals(Color.WHITE))
                { 
                    matrix[x][y] = 1;                   
                }

                String color = matrix[x][y]==1 ? "W" : "B";
                exportStr += formatStringExport(currentPx, x, y, color); // just concatenate values
                currentPx++;
            }
        }

        return img;
}

【问题讨论】:

  • 你为什么使用matrix数组?您也可以在没有此数组的情况下导出字符串。
  • @Braj,我稍后会需要那个矩阵,虽然我现在没有使用

标签: java image performance swing image-processing


【解决方案1】:

这可能是你的问题

exportStr += formatStringExport(currentPx, x, y, color);

改用StringBuilder

StringBuilder sb = new StringBuilder(imgW  * imgH * <String size per pixel>);

....

sb.append(formatStringExport(currentPx, x, y, color));

查看StringBuilder 文档了解详细信息。此外,您可以尝试减少正在创建的对象的数量。所以例如替换:

c = new Color(image.getRGB(x, y));

String color = matrix[x][y]==1 ? "W" : "B";

由...

if(image.getRGB(x, y).equals(...))

sb.append(formatStringExport(currentPx, x, y, (matrix[x][y]==1 ? "W" : "B")));

祝你好运! :)

【讨论】:

  • StringBuilder 确实提高了很多性能。谢谢!由于getRGB() 返回int,我使用if(image.getRGB(x, y)==Color.WHITE)
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多