1

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

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;
}

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

4

1 回答 1

2

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

此外,您可能希望确保不要离开界限,例如使用xand 。yMath.min(...)Math.max(...)

最后,应该是int y = round((i / sf) * o.width;因为你想得到原始比例的像素,然后与原始宽度相乘。示例:假设一个 100x100 的图像和 1.2 的缩放因子。缩放后的高度为 120,因此最高值为i119。现在,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)];
  }
}
于 2012-04-12T07:31:28.210 回答