【问题标题】:BufferedImage to 2D Array: Finding pixelated edgesBufferedImage 到 2D 数组:查找像素化边缘
【发布时间】:2014-01-26 21:10:56
【问题描述】:

我正在尝试计算 .png 文件中黑色对象的边缘。我的意思是找到构成封装对象的框的列值和行值。我为我创建的照片附加了一个链接,该链接根据我找到的值绘制了框。如您所见,顶部、底部和右侧的线条似乎正确排列,但如果您放大左侧线条,则图像的一部分位于框外。这是为什么?我有一个算法,我将在下面发布它搜索数组中的每个像素并找到像素值的最后一次出现!= 0 用于顶部、底部、左侧和右侧。由于某种原因,左侧的额外图像正在注册 == 0 的像素......这些值是否被四舍五入为零?如果有人能解释正在发生的事情,那就太好了。

这是图片的链接:http://i.imgur.com/UG8Cghe.png。你真的必须放大左侧才能看到我在说什么。下载图像和查看可能是必要的。这是一个非常小的细节。

这是将 BufferedImage(.png) 转换为 2D 数组的方法:

private static int[][] loadImageTo2D(String file_path)
{
    img = null;
    try { img = ImageIO.read(new File(file_path)); } 
    catch (IOException e) { System.out.println(e); }

    int width = img.getWidth();
    int height = img.getHeight();
    int[][] pix = new int[height][width];

    for (int row = 0; row < height; row++) 
    {
         for (int col = 0; col < width; col++) 
         {
            pix[row][col] = img.getRGB(col, row);
         }//for
    }//for

    return pix;
}//loadImageTo2D

这是我搜索边的方式:

private static int[] getPerim(int[][] pix)
{
    //Array holds object boundary edges.
    int[] lines = new int[4];
    lines[BOTTOM] = 0;
    lines[TOP] = pix.length;
    lines[LEFT] = pix[0].length;
    lines[RIGHT] = 0;

    //Top down iteration, find the first and last row and column of the 
    //actual graphic.
    for (int row = 0; row < pix.length; row++)
    {   
        for(int col = 0; col < pix[0].length; col++)
        {
            if (pix[row][col] != 0)
            {
                if (row < lines[TOP]) { lines[TOP] = row; }
                else if (row > lines[BOTTOM]) { lines[BOTTOM] = row; }
                else if (col < lines[LEFT]) { lines[LEFT] = col; }
                else if (col > lines[RIGHT]) { lines[RIGHT] = col; }
            }//if
        }//for
    }//for

    return lines;
}//getPerim

然后我使用lines[] 来绘制您在图像中看到的蓝色框。救命!

【问题讨论】:

    标签: java bufferedimage pixels


    【解决方案1】:

    删除if elseelse 部分,并将它们全部设为ifs。只有其中一个 if else 可以执行。如果像素是最下方和最左侧的像素,会发生什么?它将仅用作最底部的,因为 if-else 语句不会到达 col 部分。建议你改成

                if (row < lines[TOP]) { lines[TOP] = row; }
                if (row > lines[BOTTOM]) { lines[BOTTOM] = row; }
                if (col < lines[LEFT]) { lines[LEFT] = col; }
                if (col > lines[RIGHT]) { lines[RIGHT] = col; }
    

    不,您不能将左边框与右边框组合在一起,因为它们可以在同一个像素上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多