【问题标题】:Image interpolation - nearest neighbor (Processing)图像插值 - 最近邻(处理)
【发布时间】:2012-04-24 12:44:57
【问题描述】:

我在处理中遇到了图像插值方法的问题。这是我提出的代码,我知道它会抛出越界异常,因为外部循环比原始图像更远,但我该如何解决?

PImage nearestneighbor (PImage o, float sf)
{
  PImage out = createImage((int)(sf*o.width),(int)(sf*o.height),RGB);
  o.loadPixels();
  out.loadPixels();
  for (int i = 0; i < sf*o.height; i++)
  {
    for (int j = 0; j < sf*o.width; j++)
    {
      int y = round((o.width*i)/sf);
      int x = round(j / sf);
      out.pixels[(int)((sf*o.width*i)+j)] = o.pixels[(y+x)];
    } 
  }

  out.updatePixels();
  return out;
}

我的想法是将代表缩放图像中的点的两个分量除以比例因子并将其四舍五入以获得最近的邻居。

【问题讨论】:

    标签: java image-processing processing


    【解决方案1】:

    为了摆脱IndexOutOfBoundsException,请尝试缓存(int)(sf*o.width)(int)(sf*o.height) 的结果。

    此外,您可能希望确保 xy 不会超出界限,例如通过使用Math.min(...)Math.max(...)

    最后,它应该是int y = round((i / sf) * o.width;,因为您想获得原始比例的像素,然后与原始宽度相乘。示例:假设一个 100x100 的图像和 1.2 的缩放因子。缩放后的高度将为 120,因此 i 的最大值将为 119。现在,round((119 * 100) / 1.2) 产生 round(9916.66) = 9917。另一方面,round(119 / 1.2) * 100 产生 round(99.16) * 100 = 9900 - 这里有 17 个像素的差异。

    顺便说一句,变量名称y 在这里可能会产生误导,因为它不是 y 坐标,而是坐标 (0,y) 处像素的索引,即高度 y 处的第一个像素。

    因此您的代码可能如下所示:

    int scaledWidth = (int)(sf*o.width);
    int scaledHeight = (int)(sf*o.height);
    PImage out = createImage(scaledWidth, scaledHeight, RGB);
    o.loadPixels();
    out.loadPixels();
    for (int i = 0; i < scaledHeight; i++) {
      for (int j = 0; j < scaledWidth; j++) {
        int y = Math.min( round(i / sf), o.height ) * o.width;
        int x = Math.min( round(j / sf), o.width );
        out.pixels[(int)((scaledWidth * i) + j)] = o.pixels[(y + x)];
      }
    }
    

    【讨论】:

    • 我仍然在作业的右侧遇到越界异常( o.pixels[(y+x)] )=/
    • @TarekMerachli 您能否举例说明导致异常的初始尺寸、比例因子、比例尺寸以及 y 和 x 值?
    • 初始尺寸为 800x600,比例为 2,我检查了缩放尺寸,它们是正确的 (1600.0 x 1200.0)。当我尝试打印 x 和 y 值时,程序就会崩溃:P 真的很讨厌处理没有调试器。此外,超出范围发生在索引 480,000
    • @TarekMerachli 我忘记在我的代码中包含Math.min(...),但在正文中提到了它。这里的问题如下:i 的最大值可以是 1199,因此 1199/2 = 599.5 将被四舍五入,从而导致 600 超出范围(原始高度范围为 0-599)。我会将最小检查添加到我的答案代码中。
    • 啊,是的,你是对的:P 我把它改成了 o.width-1 和 o.height-1 因为 o.width 也让我越界了。非常感谢:)
    猜你喜欢
    • 2019-02-20
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2019-11-07
    • 2020-05-20
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多