2017-02-05 72 views
0

我想爲我的3D引擎採樣高度圖。可能發生的情況是我的地形上有更多的頂點比我的圖像中的像素更多。我創建下面的方法:插值圖像像素

public float interpolateFromImage(BufferedImage image, float x, float y){

這需要所述圖像和所述x和y座標。座標以百分比表示。 我的方法是計算附近像素和給定座標之間的距離。這工作得很好,但我最終與此: Output Image; size 1000x1000. Input is a 4x4 picture

可以清楚地看到,邊緣不像他們應該是光滑的。

我用下面的代碼:

int topLeftX = (int) (x * (image.getWidth()-1));  //index of topLeft pixel 
    int topLeftY = (int) (y * (image.getHeight()-1));  //index of topLeft pixel 

    float[] distances = new float[4]; 
    float total = 0; 
    for(int j = topLeftX ; j < topLeftX + 2; j++){   //run through all 4 nearby pixels 
     for(int k = topLeftY ; k < topLeftY + 2; k++){ 
      float dist = (float) Math.sqrt(     //pythagoras for the distance 
        (x- j/ (float)(image.getWidth()-1)) * 
          (x- j/ (float)(image.getWidth()-1)) + 
          (y- k/ (float)(image.getHeight()-1)) * 
            (y- k/ (float)(image.getHeight()-1))); 
      if(dist < 0.001){ 
       return new Color(image.getRGB(j,k)).getRed(); 
      } 
      distances[(j-topLeftX) * 2 + (k-topLeftY)] = (1f/image.getWidth())/(dist * dist); 
      total += distances[(j-topLeftX) * 2 + (k-topLeftY)]; 
     } 
    } 
    float h = 0; 
    for(int j = topLeftX ; j < topLeftX + 2; j++){ 
     for(int k = topLeftY ; k < topLeftY + 2; k++){ 
      float p = distances[(j-topLeftX) * 2 + (k-topLeftY)]/total; 
      h+= new Color(image.getRGB(j,k)).getRed() * p; 
     } 
    } 
    return h; 

有誰知道我需要怎麼改變我的代碼? 我很樂意提供任何建議和幫助:)

回答

0

您正在根據所有四個角的平方距離來衡量顏色。這裏的問題是:邊緣上的像素顏色受到拐角顏色的影響。邊上兩側的像素顏色不同,因爲它們是從一組不同的四角計算出來的。

解決方案是使用一些常見的插值,如雙線性或雙三次插值。

+0

姆姆是的......我知道它爲什麼看起來像:)我想用我自己做的東西。似乎不是最好的主意。謝謝!:) – Luecx

+1

你可以隨時進一步試驗,這是學習的最佳方式。 –