Java 图像插值-最近邻(处理)

Java 图像插值-最近邻(处理),java,image-processing,processing,Java,Image Processing,Processing,我在处理过程中遇到了图像插值方法的问题。这就是我提出的代码,我知道它会抛出一个越界异常,因为外循环比原始图像更远,但我如何修复它 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.h

我在处理过程中遇到了图像插值方法的问题。这就是我提出的代码,我知道它会抛出一个越界异常,因为外循环比原始图像更远,但我如何修复它

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;
}
PImage最近邻(PImage o,浮点sf)
{
PImage out=createImage((int)(sf*o.width),(int)(sf*o.height),RGB);
o、 loadPixels();
out.loadPixels();
对于(int i=0;i

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

要消除
索引自动边界异常
请尝试缓存
(int)(sf*o.width)
(int)(sf*o.height)
的结果

此外,您可能希望确保
x
y
不离开边界,例如使用
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)];
  }
}
int scaledWidth=(int)(sf*o.width);
整型标度高度=(整型)(sf*o.height);
PImage out=createImage(缩放宽度、缩放高度、RGB);
o、 loadPixels();
out.loadPixels();
对于(int i=0;i
我仍然在赋值的右侧得到一个越界异常(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也给了我一个越界。非常感谢:)