C++动态2D阵列到OpenCV Mat



我引用了这篇文章:如何将C++数组转换为opencv-Mat

它适用于普通的2D阵列。

然而,如果我使用DYNAMIC 2D数组作为输入,它会失败。。。

int total_row = 2;
int total_col = 4;
unsigned short **my_arr = NULL;
my_arr = new unsigned short*[total_row];
//allocate memory for each 1D array
for (int i = 0; i < total_row; i++)
{
my_arr[i] = new unsigned short[total_col];
}
//Set value into 2D array
int count = 0;
for (int i = 0; i < total_row; i++)
{
for (int j = 0; j < total_col; j++)
{
my_arr[i][j] = count;
count++;
}
}
for (int i = 0; i < total_row; i++)
{
for (int j = 0; j < total_col; j++)
{
cout << my_arr[i][j] << " ";
}
cout << endl;
}
//put that into Mat
Mat mat(total_row, total_col, CV_16UC1, my_arr);
for (int i = 0; i < mat.rows; i++)
{
for (int j = 0; j < mat.cols; j++)
{
cout << mat.at<ushort>(i, j) << " ";
}
cout << endl;
}

动态2D阵列返回:

0 1 2 3

4 5 6 7

垫返回错误

21760 88 0 0

22480 88 0 0

我错过什么了吗?非常感谢!

感谢Nicholas Betsworth!如果使用1D动态数组,它是有效的!

unsigned short *my_arr = NULL;
my_arr = new unsigned short[total_row*total_col];
for (int i = 0; i < (total_row*total_col); i++)
{
*(my_arr + i) = count;
count++;
}
Mat mat(total_row, total_col, CV_16UC1, my_arr);

最新更新