2012-04-21 49 views
1

我很新的OpenCV ... 我需要从opencv.Wat两个线性数据数组我要去值之间来预测任何直接的功能为此做...例如,我们在matlab中使用interp1函数。有没有进行一维数据插值(表查找)

tab = 
    1950 150.697 
    1960 179.323 
    1970 203.212 
    1980 226.505 
    1990 249.633 
then the population in 1975, obtained by table lookup within the matrix tab, is 

p = interp1(tab(:,1),tab(:,2),1975) 
p = 
    214.8585 

我们如何在opencv中做到这一点...请帮助我..提前感谢。

回答

2

你可以尝试使用回归函数建成的OpenCV。但你似乎是做简单的线性插值可能更容易只是把它写自己。

double interpolate(int x1, double y1, int x2, double y2, int targetX) 
{ 
    int diffX = x2 - x1; 
    double diffY = y2 - y1; 
    int diffTarget = targetX - x1; 

    return y1 + (diffTarget * diffY)/diffX; 
} 

此函数线性地插入给两个给定的数据点的目标值。

如果你想使用它像MATLAB的功能,同时提供所有数据点,你需要挑选其中最近的两个邻居功能。事情是这样的:

double interpolate(Mat X, Mat Y, int targetX) 
{ 
    Mat dist = abs(X-targetX); 
    double minVal, maxVal; 
    Point minLoc1, minLoc2, maxLoc; 

    // find the nearest neighbour 
    Mat mask = Mat::ones(X.rows, X.cols, CV_8UC1); 
    minMaxLoc(dist,&minVal, &maxVal, &minLoc1, &maxLoc, mask); 

    // mask out the nearest neighbour and search for the second nearest neighbour 
    mask.at<uchar>(minLoc1) = 0; 
    minMaxLoc(dist,&minVal, &maxVal, &minLoc2, &maxLoc, mask); 

    // use the two nearest neighbours to interpolate the target value 
    double res = interpolate(X.at<int>(minLoc1), Y.at<double>(minLoc1), X.at<int>(minLoc2), Y.at<double>(minLoc2), targetX); 
    return res; 
} 

这里是展示如何使用它的一个小例子:

int main() 
{ 
    printf("res = %f\n", interpolate(1970, 203.212, 1980, 226.505, 1975)); 

    Mat X = (Mat_<int>(5, 1) << 
    1950, 1960, 1970, 1980, 1990); 
    Mat Y = (Mat_<double>(5, 1) << 
    150.697, 179.323, 203.212, 226.505, 249.633); 
    printf("res = %f\n", interpolate(X, Y, 1975)); 

    return 0; 
} 

我没有广泛测试此。所以你可能需要修复一些错误。

+0

非常感谢......我得到的输出... – aranga 2012-04-23 05:58:14

+0

如何在世界上是 双插值(马太福音X,垫Y,INT targetX) 与 内插(1970年,203.212,1980年,226.505,1975年兼容)???? – 2013-01-20 04:24:14

+0

你是什么意思兼容?它们是两种不同的功能。一,二数据点,数据点的两个矩阵之间的其他之间进行内插。 – sietschie 2013-01-20 15:27:35