Thursday, October 23, 2008

Interpolate an array to twice its size in VB.NET

I had an array that I wanted to "interpolate".  The simplified version is the array (one-dimensional) had the following values:

011000

Now this array is a one dimensional array that contains values for an image. For this example, the width of the image is 2 digits.  I wanted to interpolate this array so that the width of the image is 4 digits.

Initially my thought was just to do this:

001111000000

This was simple as I just looped through the original array as such:

for index = 0 to oldarray.length - 1
    newarray[index*2] = oldarray[index]
    newarray[index*2 + 1] = oldarray[index]
end for


But the problem with this is that the old image looked like this:

01
10
00

The new image looks like this:
0011
1100
0000

Which is fine, except when I realized that I interpolated ONLY the WIDTH of the array, and not the height.  What I wanted was something like this:

001100111100110000000000

0011
0011
1100
1100
0000
0000

Now for some reason I couldn't figure this out.  But the solution is actually quite simple.  You have to set 4 values for each one in the old array.  In the above example, I interpolate the width, now I just need to interpolate the height.  Below is the example.

     For index As Integer = 0 To oldarray.length - 1
        If (index > 0 AndAlso (index Mod NEWARRAYWIDTH/ 2))) = 0) Then // I know what the width of the new image will be, and the old one is half as large
          row = row + 1
        End If
        newIndex = index Mod CInt((NEWARRAYWIDTH / 2))
        nearray((row * 2) * NEWARRAYWIDTH + (newIndex * 2)) = oldarray(index)
        nearray((row * 2) * NEWARRAYWIDTH + ((newIndex * 2) + 1)) = oldarray(index)
        nearray(((row * 2) + 1) * NEWARRAYWIDTH + (newIndex * 2)) = oldarray(index)
        nearray(((row * 2) + 1) * NEWARRAYWIDTH + ((newIndex * 2) + 1)) = oldarray(index)
      Next

No comments: