【问题标题】:c++ OpenCV Turn a Mat into a 1 Dimensional Arrayc++ OpenCV 将 Mat 变成一维数组
【发布时间】:2015-03-14 22:00:20
【问题描述】:

我有这个Mat

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

取自:

float testDataFloat[386][2];

但我不知道如何把它变成一维数组。

有什么帮助吗?

【问题讨论】:

  • float* testData1D = testDataFloat;
  • “float (*)[2]”类型的值不能用于初始化“float *”类型的实体
  • 对不起,float* testData1D = (float*)testDataFloat;
  • 等等,你想把整个二维数组转换成一维数组,还是只转换一列?
  • 我想将检测到的特征提供给支持向量机进行预测

标签: c++ arrays opencv mat


【解决方案1】:

样本包括:

  1. 将浮点二维数组转换为浮点一维数组的直接方法。
  2. 从二维浮点数组创建 cv::Mat 的方法
  3. 从没有填充的二维 cv::Mat 创建一维浮点数组的方法(例如,步长 = 单行的大小)

这个对我有用:

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

}

【讨论】:

  • Mat 提供一维数组,这是否正确? Mat testDataMat1D(height, 0, CV_32FC1, testData1D);
  • 一维数组有大小为width*height的元素(转换后,也可以使用arraySize),不能在矩阵中使用0 cols,所以调用应该是:Mat testDataMat1D(height*width, 1, CV_32FC1, testData1D); ...但您可以直接使用二维数组将其输入 cv::Mat...
  • 是的,我的意思是 1 而不是 0,但我没有想到 height*width,谢谢!无论如何,testDataMat1D 是否可以清晰地输入到SVM.predict 中?
  • 它类似于stackoverflow.com/questions/14694810/…,我认为SVM.predict 应该没问题,尽管我对SVM 没有任何经验。
  • @MLMLTL 不,您不能使用具有多行的Mat 来输入predict()。它需要单行多 Mat
猜你喜欢
  • 1970-01-01
  • 2021-02-21
  • 2012-09-20
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 2016-08-31
相关资源
最近更新 更多