OpenCV以一种有效的方式从uchar数组创建序列

OpenCV create a sequence from an array of uchar in an efficient way

本文关键字:uchar 方式 数组 创建 有效 一种 OpenCV      更新时间:2023-10-16

我正在移植一些使用OpenCV的代码,只是为了适合椭圆。我以后可能会重写它,但现在我需要使用OpenCV例程。这段代码只有几行,但我不得不改变几乎所有的东西,因为cvFitEllipse2()的配置文件已经改变了。

我的问题是以下一个:转换点的数组(对uchar)成的东西,我可以饲料cvFitEllipse2()与

我没有找到很多代码样本,我发现OpenCV的文档记录很差(但因为我是OpenCV的新手,也许这种感觉是错误的)。无论如何,这是我写的:

/* centers is the input uchar array */
CvBox2D box;    //output
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq(CV_32FC2, sizeof(CvSeq), sizeof(CvPoint2D32f), storage);
for(int h=0; h<mm; ++h) 
{
    CvPoint2D32f p;
    p.x = (float)centers[h].x;
    p.y = (float)centers[h].y;
    cvSeqPush(seq, &p);
}
// Fits ellipse to current contour.
box = cvFitEllipse2(seq);

问题:这段代码比原来的代码慢。

    是否有任何方法可以预先分配seq所需的内存?(使用CvMemStorage对象)
  • 有没有更好(更简单)的?容器比CvSeq吗?
  • 我可以用更快的东西代替cvSeqPush吗?

谢谢你的帮助!

我假设centers是点的向量。

如果你乐于使用c++接口而不是旧的,那么你的痛苦就结束了。

根据中心的声明方式,可以:

vector<cv::Point> centers;
RotatedRect rect = fitEllipse(centers);

或核心方法:

struct {
    uchar x, y
} myPoint;
vector<myPoint> centers;
...
int sz = centers.size();
// if you have a different type for x and y, modify here to CV_MY_TYPE
// Here I have taken a pointer to the vector data storage, 
// and fed it into the Mat.
// Check Mat documentation on constructors
Mat pts(1,sz,CV_8UC2, (void*)&centers[0].x); 
RotatedRect rect = fitEllipse(pts);
...
// take care not to change/ delete your vector 
// before finishing with the pts Mat.

编辑

我已经将类型修改为UCHAR