c ++ OpenCV将Mat转换为1维数组

时间:2015-01-16 10:09:22

标签: c++ arrays opencv mat

我有Mat

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

从中获取:

float testDataFloat[386][2];

但我无法弄清楚如何将其变成1维阵列。

任何帮助?

1 个答案:

答案 0 :(得分:1)

样本包括:

  1. 从float 2d数组转换为float 1d数组的直接方法。
  2. 从2D浮点数组创建cv :: Mat的方法
  3. 从没有填充的2D cv :: Mat创建一维浮点数组的方法(例如,stepsize =单行的大小)
  4. 这个适用于我:

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