使用动态分配的数据初始化cv :: Mat

时间:2013-08-14 13:51:50

标签: c++ opencv

最近,我尝试使用动态分配的数据初始化cv::Mat并失败。

// Create matrix
size_t sizeA = 30, sizeB = 30;
double** m = new double*[sizeA];

// Fill matrix with data
for(int i = 0; i < sizeA; i++)
{
    m[i] = new double[sizeB];
    for(int j = 0; j < sizeB; j++)
        m[i][j] = (i + 1) * (j + 1);
}

// Compute step between two vectors (not sizeof(double) * sizeB !)
size_t step = reinterpret_cast<size_t>(m[1]) - reinterpret_cast<size_t>(m[0]);

// Copy to matrix (use clone() to see if the data can be addressed properly)
cv::Mat M = cv::Mat(sizeA, sizeB, CV_64FC1, m[0], step).clone();

// delete allocated data
for(int i = 0; i < sizeA; i++)
    delete[] m[i];
delete[] m;

显然,行之间的步骤不一致(大多数情况下,但有时不是),因为每行都是独立分配的。 为了表明我只检查了每一行并检测到几个不一致的步骤:

for(int i = 2; i < sizeA; i++)
{
    if(step != reinterpret_cast<size_t>(m[i]) - reinterpret_cast<size_t>(m[i-1]))
    {
        std::cout << "Inconsistent step detected between element " << i-1 << " and " << i << " : ";
        std::cout << reinterpret_cast<size_t>(m[i]) - reinterpret_cast<size_t>(m[i-1]) << std::endl;
    }
}

我的问题:有没有办法动态分配矩阵并将其传递给cv :: Mat?

1 个答案:

答案 0 :(得分:1)

这个怎么样?

double* m = new double[sizeA*sizeB];
size_t step = sizeof(double)*sizeB;