线性插值公式
现在又两个数,2和6,在中间插入一个数值,那么我们一般用(2+6)/2 = 4,这样在中间插入一个值。
那么在A和B之间插入数据的公式为(A+B)/2。
一维数据线性插值
有这样一个长度为6一维数组:
{1,5,7,9,10,14}
在每两个数中插入一个数值,之后得到一个长度为11的数组。
只需要先调整原数据的位置,将索引*2得到在新数组中的位置,然后再利用上面的插值公式 d[index] = (d[index-1] + d[index+1])/2。代码如下:
const int length = 6;
const int newLength = 2*length-1;
int array[length] = {1,5,7,9,10,14};
int newArray[newLength];
for(int index = 0;index < newLength;index+=2)
{
newArray[index] = array[index/2];
}
for(int index = 1;index < newLength;index+=2)
{
newArray[index] = (newArray[index - 1] + newArray[index + 1])/2;
}
这样就得到了新的数组{1,3,5,6,7,8,9,9,10,12,14,}。
二维矩阵插值公式
先将问题简化,这里以一个4*4的数据插值为7*7的数据为例。
{{1, 5, 4, 10},
{ 2, 6, 1, 9},
{10, 2, 5, 1},
{9, 14, 2, 6}}
将数据放到新的矩阵中之后,先横向进行插值。
{{ 1, 3, 5, 4, 4, 7, 10,}
{ X, X, X, X, X, X, X,}
{ 2, 4, 6, 3, 1, 5, 9,}
{ X, X, X, X, X, X, X,}
{ 10, 6, 2, 3, 5, 3, 1,}
{ X, X, X, X, X, X, X,}
{ 9, 11, 14, 8, 2, 4, 6,}}
X表示还未插值的地方。
然后再纵向进行插值。
{{ 1, 3, 5, 4, 4, 7, 10,}
{ 1, 3, 5, 3, 2, 6, 9,}
{ 2, 4, 6, 3, 1, 5, 9,}
{ 6, 5, 4, 3, 3, 4, 5,}
{ 10, 6, 2, 3, 5, 3, 1,}
{ 9, 8, 8, 5, 3, 3, 3,}
{ 9, 11, 14, 8, 2, 4, 6,}}
这样就完成了一个二维矩阵的插值。
const int width = 4;
const int height = 4;
const int newWidth = 2*width - 1;
const int newHeight = newWidth;
int array[width][height] = {{1,5,4,10},
{2,6,1,9},
{10,2,5,1},
{9,14,2,6}};
int newArray[newWidth][newHeight];
for(int i =0; i <newWidth*newHeight;i++)
{
newArray[i/newWidth][i%newWidth] = 0;
}
for(int i = 0;i < newWidth*newHeight;i+=2)
{
int hi = i/newWidth;
int wi = i%newWidth;
newArray[wi][hi] = array[wi/2][hi/2];
}
for(int r = 0;r < newHeight;r+=2)
{
for(int l = 1;l < newWidth;l+=2)
{
newArray[r][l] = (newArray[r][l -1] + newArray[r][l + 1])/2;
}
}
for(int l = 0;l < newWidth;l++)
{
for(int r = 1;r < newHeight;r+=2)
{
newArray[r][l] = (newArray[r - 1][l] + newArray[r + 1][l])/2;
}
}
std::cerr << "{";
for(int w = 0;w < newHeight;w++)
{
std::cerr << "{" ;
for(int h = 0;h < newHeight;h++)
{
std::cerr <<" "<< newArray[w][h] << ",";
}
std::cerr << "}" << std::endl;
}
std::cerr << "}";
补充
将线性插值的数据可视化:http://cppdebug.com/archives/189
文章评论