0

I've ref the article: How to convert C++ array to opencv Mat

It's work for normal 2D array.

However, if I use DYNAMIC 2D array as input, it fail...

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;
}

Dynamic 2D array return:

0 1 2 3

4 5 6 7

Mat return INCORRECT:

21760 88 0 0

22480 88 0 0

Did I miss something? Thanks a lot!

Hughes
  • 121
  • 1
  • 11
  • 4
    I think OpenCV expects a pointer to a sequential partition of memory. See [this answer](https://stackoverflow.com/questions/25136781/opencv-create-mat-from-array-in-heap) for a solution. – Nicholas Betsworth Aug 27 '20 at 08:18
  • @NicholasBetsworth That's what I need! Thank you so much!! – Hughes Aug 27 '20 at 08:50

1 Answers1

3

Thanks for Nicholas Betsworth! If using 1D dynamic array, it's working!

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);
Hughes
  • 121
  • 1
  • 11