c++ OpenCV Turn a Mat into a 1 Dimensional Array

旧时模样 提交于 2019-12-12 01:55:49

问题


I have this Mat:

Mat testDataMat(386, 2, CV_32FC1, testDataFloat);

Which takes in from:

float testDataFloat[386][2];

But I can't figure out how to turn it into a 1 Dimensional Array.

Any help?


回答1:


sample includes:

  1. direct method to convert from float 2d array to float 1d array.
  2. way to create a cv::Mat from 2D float array
  3. way to create 1D float array from a 2D cv::Mat that has no padding (e.g. stepsize = size of a single row)

This one works for me:

int main()
{
    const int width = 2;
    const int height = 386;
    float testDataFloat[height][width];

    // create/initialize testdata
    for(unsigned int j=0; j<height; ++j)
        for(unsigned int i=0; i<width; ++i)
        {
            if(j%5 == 0)
                testDataFloat[j][i] = 0.0f;
            else
                testDataFloat[j][i] = 1.0f;
        }

    // -----------------------------------------------------------
    // Direct convert from 2D array to 1D array:
    float * testData1DDirect = (float*)testDataFloat;



    // -----------------------------------------------------------
    // create Mat with 2D array as input:
    cv::Mat testDataMat(height, width, CV_32FC1, testDataFloat);

    // convert from Mat to 1D array
    // this works only if there is no padding in the matrix.
    float * testData1D = (float*)testDataMat.data;


    // test whether the arrays are correct
    for(unsigned int i=0; i<width*height; ++i)
    {
        if(testData1D[i] != testData1DDirect[i])
            std::cout << "ERROR at position: " << i << std::endl;
    }

    // output the Mat as an image:
    cv::imshow("test", testDataMat);
    cv::waitKey(0);

}


来源:https://stackoverflow.com/questions/27981571/c-opencv-turn-a-mat-into-a-1-dimensional-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!