2014-03-03 120 views
1

我目前正在c#中進行3D遊戲。我有一個稱爲data的二維數組,其中我得到的z值爲我的xy值。 例如:2D陣列插值

data[x,y] = z; 
data[1,2] = 4; 
data[2,4] = 5; 

等 我的問題是,這是非常模糊的,我還需要計算(內插)的值例如X = 1.5和y = 2.5。我怎樣才能達到這個值,並有任何可用的功能?

謝謝

+1

怎麼辦你的意思是'x = 1,5和y = 2,5' – Muctadir

+0

哦,我很抱歉,我是歐洲人,我的意思是x = 1.5,y = 2.5 – hashtag7

+1

你必須首先決定插值策略。 –

回答

10

也許雙線性插值可以在場景中使用:

float fractionX = ... //the fraction part of the x coordinate 
float integerX = ... //the integer part of the x coordinate 
float fractionY, integerY = ... 
interpolatedValue = (1 - fractionX) * 
         ((1 - fractionY) * data[integerX, integerY] + 
         fractionY * data[integerX, integerY + 1]) + 
        fractionX * 
         ((1 - fractionY) * data[integerX + 1, integerY] + 
         fractionY * data[integerX + 1, integerY + 1]); 

插值之間0,4,1 3得出以下結果:

Bilinear interpolation

如果你已經對高度圖進行了三角測量,酒吧ycentric插值可能更合適:

//Assuming the following triangle alignment: 
// 1 +--+--+--+ 
// | /| /| /| 
// |/ |/ |/ | 
// 0 +--+--+--+ 

if (fractionX < fractionY) //the upper triangle 
{ 
    interpolatedValue = (1 - fractionY) * data[integerX, integerY] + 
         fractionX * data[integerX + 1, integerY + 1] + 
         (fractionY - fractionX) * data[integerX, integerY + 1]; 
} 
else //the lower triangle 
{ 
    interpolatedValue = (1 - fractionX) * data[integerX, integerY] + 
         fractionY * data[integerX + 1, integerY + 1] + 
         (fractionX - fractionY) * data[integerX + 1, integerY]; 
} 

插值和3之間0,4,1得到下列結果:

Barycentric interpolation

1

您有兩個已知點:

A = (1,2) = 4 
B = (2,4) = 5 

而你想計算的值

C = (1.5, 2.5) = ??? 

下面是您的線性示例中的一個想法。計算每個軸的線性。因此,與X開始:

Ax = (1) = 4 
Bx = (2) = 5 
so you calculate Cx as: 
Cx = (1.5) = 4.5 

然後計算爲y軸的直線:

Ay = (2) = 4 
By = (4) = 5 
and calculate Cy as: 
Cy = (2.5) = 4.25 

然後平均Cx和Cy得到C(X,Y)

C(1.5, 2.5) = (Cx + Cy) * 0.5 = 4.375 
+0

兩點定義了一條線,所以問題在這裏沒有解決。你所做的是盲目平均。 – ja72

+0

@ ja72不,它不是盲目的平均。這基本上是雙線性插值。我的答案中列出了更一般的形式。 –