OpenCV的"calcCovarMatrix"函数中"const Mat*样本"参数的工作原理?

Workings of ``const Mat* samples`` param in OpenCV's ``calcCovarMatrix`` function?

本文关键字:工作 参数 样本 Mat 函数 calcCovarMatrix const OpenCV      更新时间:2023-10-16

我正在尝试计算 OpenCV 中多个矩阵的协方差矩阵,并看到了 2 个版本的calcCovarMatrix。我很好奇,想使用重载版本,它将const Mat* samples, int nsamples作为前 2 个参数。

问题:samples参数是什么?它是指向 Mats 向量第一项的指针吗?为什么它本身不是向量?一个人传递什么/参数如何工作?

PS:我不想使用函数的其他重载版本!我想了解我询问的版本中使用的实际代码。

我相信OpenCV的作者更喜欢const Mat*int对论证而不是std::vector,因为这更灵活。

想象一个函数必须处理一系列特定的对象。

在C++中,一系列对象可以用std::vector存储。但是,如果该对象的系列是静态常量,即可以在编译时定义呢?该对象的普通旧 C 数组也可以完成这项工作。

可以处理这样一系列对象的函数可以接受const std::vector&。如果应用于 C 数组,则必须构建一个临时向量实例。C++代码相对简单,但它在胃里留下了一种不安的感觉,因为数组内容必须复制到临时std::vector实例中才能将其传递给函数。

相反的情况:该函数接受指向启动对象的指针和一个计数(就像 C 中通常的那样)。这样的函数可以应用于 C 数组以及std::vector,因为std::vector提供了一个data()方法,该方法提供指向其第一个元素的 const 指针和一个size()方法。此外,允许向量元素像在 C 数组中一样连续存储。

所以,我的简单例子:

#include <cassert>
#include <cmath>
#include <iostream>
#include <vector>
// Pi (from Windows 7 calculator)
const float Pi = 3.1415926535897932384626433832795;
struct Point {
float x, y;
};
std::ostream& operator<<(std::ostream &out, const Point &point)
{
return out << '(' << point.x << ", " << point.y << ')';
}
Point average(const Point *points, size_t size)
{
assert(size > 0);
Point sum = points[0];
for (size_t i = 1; i < size; ++i) {
sum.x += points[i].x; sum.y += points[i].y;
}
return { sum.x / (unsigned)size, sum.y / (unsigned)size };
}
static const Point square[] = {
{ -0.5f, -0.5f },
{ +0.5f, -0.5f },
{ +0.5f, +0.5f },
{ -0.5f, +0.5f }
};
static const size_t sizeSquare = sizeof square / sizeof *square;
int main()
{
// process points of a static const square (using average() with an array)
std::cout << "CoG of " << sizeSquare << " points of square: "
<< average(square, sizeSquare) << 'n';
// build a tesselated circle
std::vector<Point> circle;
const unsigned n = 16;
for (unsigned i = 0; i < n; ++i) {
const float angle = i * 2 * Pi / n;
circle.push_back({ std::sin(angle), std::cos(angle) });
}
// process points of that circle (using average() with a vector)
std::cout << "CoG of " << circle.size() << " points of circle: "
<< average(circle.data(), circle.size()) << 'n';
// done
return 0;
}

输出:

CoG of 4 points of square: (0, 0)
CoG of 16 points of circle: (-5.58794e-09, 4.47035e-08)

科里鲁的现场演示

为方便起见,可以为std::vector添加以下替代定义:

static inline Point average(const std::vector<Point> &points)
{
return average(points.data(), points.size());
}

通用解决方案将提供具有两个迭代器的替代方案,这些迭代器可以应用于任何容器。(C++标准库有很多这方面的示例。

我只能假设OpenCV作者专注于性能而不是灵活性(但这只是我个人的猜测)。