Initialize cv::Mat with dynamically allocated data
Recently I tried to initialize a cv::Mat with dynamically allocated data
and failed.
// 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;
Obviously the step between the rows are not consistent (most of the case
it is, but sometimes not) because every row is alloced independently. To
show that I simply checked every row and detected several inconsistent
steps:
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;
}
}
My Question: Is there any way to dynamically allocate a matrix and passing
it to cv::Mat?
No comments:
Post a Comment