您可以尝试使用 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;
}
我没有对此进行广泛的测试。所以你可能需要修复一些错误。