-2

I'm facing a strange problem.

My Mat is declared as:

cv::Mat matr(src.rows, src.cols, CV_32FC1);

If i print it using cout<<matr I get all the data in range from 0 to 255 and everything is fine.

If I try to access using this cycle:

float* matrF= (float*)matr.data;

for (int r=0; r<matrF.rows; r++)
  {
    for (int c=0; c<matrF.cols; c++)
    {
      std::cout<<matrF[r*matr.cols+c]<<std::endl;
    }
  }

I get many values like: 4.684e-42, 2.223e-22 ecc.

If I use

for (int r=0; r<matrF.rows; r++)
      {
        for (int c=0; c<matrF.cols; c++)
        {
          std::cout<<matr.data[r*matr.cols+c]<<std::endl;
        }
      }

It print some random char and no values.

Ho can I access the element printed using cout<<matr ? I don't want to use function from openCV to access them, I'm trying to loop over the matr.data...

I cant't use mat.at<float> or .step1(). Thanks.

---------- SOLUTION

if instead of

for (int r=0; r<matrF.rows; r++)
  {
    for (int c=0; c<matrF.cols; c++)
    {
      std::cout<<matrF.data[r*matr.cols+c]<<std::endl;
    }
  }

I use

for (int r=0; r<matrF.rows; r++)
  {
    for (int c=0; c<matrF.cols; c++)
    {
      float val = matF.data[r*matr.cols+c];
      std::cout<<val<<std::endl;
    }
  }

the problem disappears.

0abc0cba0
  • 7
  • 5
  • Just found out the problem. Could someone explain that? I edit my post. – 0abc0cba0 Nov 11 '21 at 10:55
  • Inszeadt of r*matr.cols use r*matr.step or rowPrt(r) if you want to make it stable for all kind of matrices (which can easily have a padding at the end of each row). .at(row, col) is another fast (in release mode), nice, and well readable way. – Micka Nov 11 '21 at 12:32

1 Answers1

-1

It is highly possibly that it is not continuous. Then you cannot use matr.data to see all elements.

Please read this tutorial to see what to do: https://docs.opencv.org/4.x/db/da5/tutorial_how_to_scan_images.html

ch271828n
  • 15,854
  • 5
  • 53
  • 88