Bilinear interpolation is trivial to calculate. But I need an algorithm that performs an INVERSE operation. (the algorithm will be useful to me in pseudocode or any widely used computer language)
For example, an implementation of Visual Basic bilinear interpolation is presented here.
' xyWgt ranges (0..1) in x and y. (0,0) will return X0Y0,
(0,1) will return X0Y1, etc.
' For example, if xyWgt is relative location within an image,
' and the XnYn values are GPS coords at the 4 corners of the image,
' The result is GPS coord corresponding to xyWgt.
' E.g. given (0.5, 0.5), the result will be the GPS coord at center of image.
Public Function Lerp2D(xyWgt As Point2D, X0Y0 As Point2D, X1Y0 As Point2D, X0Y1 As Point2D, X1Y1 As Point2D) As Point2D
Dim xY0 As Point2D = Lerp(X0Y0, X1Y0, xyWgt.X)
Dim xY1 As Point2D = Lerp(X0Y1, X1Y1, xyWgt.X)
Dim xy As Point2D = Lerp(xY0, xY1, xyWgt.Y)
Return xy
End Function
Where
' Weighted Average of two points.
Public Function Lerp(ByVal a As Point2D, ByVal b As Point2D, ByVal wgtB As Double) As Point2D
Return New Point2D(Lerp(a.X, b.X, wgtB), Lerp(a.Y, b.Y, wgtB))
End Function
and
' Weighted Average of two numbers.
' When wgtB==0, returns a, when wgtB==1, returns b.
' Implicitly, wgtA = 1 - wgtB. That is, the weights are normalized.
Public Function Lerp(ByVal a As Double, ByVal b As Double, ByVal wgtB As Double) As Double
Return a + (wgtB * (b - a))
End Function
In 1-D, I defined the inverse Lerp function:
' Calculate wgtB that would return result, if did Lerp(a, b, wgtB).
' That is, where result is, w.r.t. a and b.
' < 0 is before a, > 1 is after b.
Public Function WgtFromResult(ByVal a As Double, ByVal b As Double, ByVal result As Double) As Double
Dim denominator As Double = b - a
If Math.Abs(denominator) < 0.00000001 Then
' Avoid divide-by-zero (a & b are nearly equal).
If Math.Abs(result - a) < 0.00000001 Then
' Result is close to a (but also to b): Give simplest answer: average them.
Return 0.5
End If
' Cannot compute.
Return Double.NaN
End If
' result = a + (wgt * (b - a)) =>
' wgt * (b - a) = (result - a) =>
Dim wgt As Double = (result - a) / denominator
'Dim verify As Double = Lerp(a, b, wgt)
'If Not NearlyEqual(result, verify) Then
' Dim test = 0 ' test
'End If
Return wgt
End Function
Now I need to do the same in 2-D:
' Returns xyWgt, which if given to Lerp2D, would return this "xy".
' So if xy = X0Y0, will return (0, 0). if xy = X1Y0, will return (1, 0), etc.
' For example, if 4 corners are GPS coordinates in corners of an image,
' and pass in a GPS coordinate,
' returns relative location within the image.
Public Function InverseLerp2D(xy As Point2D, X0Y0 As Point2D, X1Y0 As Point2D, X0Y1 As Point2D, X1Y1 As Point2D) As Point2D
' TODO ????
End Function