我正在尝试对一组点使用多项式回归以将它们映射到曲线。当我构造设计矩阵时,分配值似乎没有正确处理。构造的矩阵是3 x n矩阵,其中n是点数,并且与设计矩阵一样,第一列应为全1(来自// HERE IS ASSIGNMENT
部分)。当我打印矩阵时,第一列充满随机数,经常是infs和nans。常量分配怎么可能?由于矩阵中没有数字和infs,因此对矩阵进行数学运算会导致其他问题。
下面的代码是构造矩阵的位置。
for (auto it = lane_lines.begin(); it != lane_lines.end(); it++) {
vector<pair<Point, Point> > lines = *it;
// Remove random line clusters
if (lines.size() < 10) {
it = --lane_lines.erase(it);
continue;
}
Mat design(lines.size() * 2, 3, CV_64FC1);
Mat y_vec(lines.size() * 2, 1, CV_64FC1);
for (int i = 0; i < lines.size(); i += 2) {
// HERE IS ASSIGNMENT
design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2, 1) = lines[i].first.x;
design.at<double>(i * 2, 2) = pow(lines[i].first.x, 2);
design.at<double>(i * 2 + 1, 0) = 1.0;
design.at<double>(i * 2 + 1, 1) = lines[i].second.x;
design.at<double>(i * 2 + 1, 2) = pow(lines[i].second.x, 2);
y_vec.at<double>(i * 2, 0) = lines[i].first.y;
y_vec.at<double>(i * 2 + 1, 0) = lines[i].second.y;
}
// TODO: Deal with all the NaNs
cout << design << endl;
cout << design.t() * design << endl;
cout << "DET: " << determinant(design.t() * design) << endl << endl;
Mat std_poly = ((design.t() * design).inv() * design.t()) * y_vec;
double a = std_poly.at<double>(0, 2);
double b = std_poly.at<double>(0, 1);
double c = std_poly.at<double>(0, 0);
double h = -b / (2 * a == 0 ? numeric_limits<double>::min() : 2 * a);
double k = c - (a * pow(h, 2));
tuple<double, double, double, Point> curve(a, b, c, Point(h, k));
curves.push_back(curve);
}
编辑:问题似乎是针对不同的数据集随机出现的。
最佳答案
首先看一下您的代码:
for (int i = 0; i < lines.size(); i += 2) {
// HERE IS ASSIGNMENT
design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2, 1) = lines[i].first.x;
design.at<double>(i * 2, 2) = pow(lines[i].first.x, 2);
design.at<double>(i * 2 + 1, 0) = 1.0;
design.at<double>(i * 2 + 1, 1) = lines[i].second.x;
design.at<double>(i * 2 + 1, 2) = pow(lines[i].second.x, 2);
y_vec.at<double>(i * 2, 0) = lines[i].first.y;
y_vec.at<double>(i * 2 + 1, 0) = lines[i].second.y;
}
对于第一次迭代,
i=0
这两行design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2 + 1, 0) = 1.0;
成为:
design.at<double>(0, 0) = 1.0;
design.at<double>(1, 0) = 1.0;
接下来的迭代是
i=2
,因为i+=2
处于循环中,因此上述几行变为:design.at<double>(4, 0) = 1.0;
design.at<double>(5, 0) = 1.0;
我认为您应该将
i+=2
更改为i++
以解决此问题。注意:您的代码可能还有其他问题。
关于c++ - 矩阵值在OpenCV中为inf/nan,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49692515/