2012-04-12 104 views
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; 
} 

我的想法是將表示縮放圖像中的點的兩個分量除以縮放因子並四捨五入以獲得最近的鄰居。

回答

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)]; 
    } 
} 
+0

我仍然得到一個出界異常的分配(o.pixels [(Y + X)])的右側=/ – AuthenticReplica 2012-04-12 08:07:37

+0

@TarekMerachli您能舉出一個初始維度,比例因子,縮放維度以及導致異常的y和x值的例子嗎? – Thomas 2012-04-12 08:36:55

+0

初始尺寸爲800x600,比例爲2,我檢查了比例尺寸,它們是正確的(1600.0 x 1200.0)。當我嘗試打印x和y值時,程序崩潰:P真的很討厭Processing沒有調試器。此外,出現在索引480,000 – AuthenticReplica 2012-04-12 08:40:45