0

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

// 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?

4

1 回答 1

1

这个怎么样?

double* m = new double[sizeA*sizeB];
size_t step = sizeof(double)*sizeB;
于 2013-08-14T14:03:27.090 回答