是否有任何直接功能来执行1D数据插值(表查找)

时间:2012-04-21 10:46:33

标签: matlab opencv computer-vision

我对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中这样做...请帮助我......谢谢。

1 个答案:

答案 0 :(得分: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;
}

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