如何在以下代码中将Mat_转换为Mat?

时间:2014-03-17 04:47:16

标签: c++ opencv

下面的

是这个link的opencv SVM教程的片段。在那段代码中就是这段代码' Mat sampleMat =(Mat_(1,2)<< j,i);'。我不需要使用Mat_模板,而是需要使用常规的Mat对象。我希望有人能告诉我如何将Mat_转换为上一行中的Mat。

我尝试了Mat sampleMat = (Mat(1,2, CV_32FC1) << j,i); //但却得到了很长的错误 我尝试了Mat sampleMat = Mat(1,2, CV_32FC1) << j,i; //相同的长页错误

我只需要在页面顶部的链接处运行代码,而无需使用Mat_并仅使用Mat代替...如果有人可以告诉我如何编写该行,我会很感激它

  for (int i = 0; i < image.rows; ++i)
         for (int j = 0; j < image.cols; ++j)
         {
             Mat sampleMat = (Mat_<float>(1,2) << j,i);
             float response = SVM.predict(sampleMat);

             if (response == 1)
                 image.at<Vec3b>(i,j)  = green;
             else if (response == -1)
                  image.at<Vec3b>(i,j)  = blue;
         }

编辑:尝试按以下方式运行,但收到​​错误

 Vec3b green(0,255,0), blue (255,0,0);
    // Show the decision regions given by the SVM
    for (int i = 0; i < image.rows; ++i)
        for (int j = 0; j < image.cols; ++j)
        {

    Mat sampleMat(1, 2, CV_32F);
    float * const pmat = sampleMat.ptr<float>();
    pmat[0] = i;
    pmat[1] = j;

            float response = SVM.predict(sampleMat);

            if (response == 1)
         pmat[0]  = green;
        pmat[1] = green;
            else if (response == -1)
          pmat[0]  = blue;
             pmat[1]  = blue;
    }

我认为你已经足够了解所以我不需要错误=)

1 个答案:

答案 0 :(得分:0)

直接设置值:

Mat sampleMat(1, 2, CV_32F);
sampleMat.at<float>(0,1) = j;
sampleMat.at<float>(0,2) = i;

Mat sampleMat(1, 2, CV_32F);
float * const pmat = sampleMat.ptr<float>();
pmat[0] = j;
pmat[1] = i;

附录:

看到你的循环,在SVM.predict不修改sampleMat的情况下,你可以提高效率。您可以每行只设置一次图像行,而不是一直这样做:

for (int i = 0; i < image.rows; ++i)
{
  Mat sampleMat(1, 2, CV_32F);
  sampleMat.at<float>(0, 2) = i;

  for (int j = 0; j < image.cols; ++j)
  {
    sampleMat.at<float>(0, 1) = j;
    ...
  }
}
相关问题