-1

I need to access a cv::Mat, but i don't have to know the sizeof the Matrix, so is there a way to access the elements of a cv::Mat for all the sizes? I mean without doing a switch on the type of the Matrix.

So this is what i have :

int image_type = image.type();
switch (image_type)
{
case CV_32F :
    return image.at<float>(i,j);
case CV_8U :
    return (float)image.at<uchar>(i,j);
.
.
.
default:
    std::string msg = "Exception : cannot access IMAGE of type : " + image_type;
    throw std::exception(msg.c_str());
    break;
}

what I'm doing is accessing the data of the matrix and then transform it to floats (since i work with matrix with 32F max), this code is working fine but I'm looking for something like this : float x = image.at(i,j); but that would work for a matrix 8U and others ...

Thanks !

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36
  • The matrix has `mat.rows` and `mat.cols`. But I think you mean the element type? You can interpret the element type with `mat.type()` or `.depth` and `.channels`. – Micka Jul 31 '14 at 08:05
  • I think that my question was not clear, I know that i can access the elements of the Matrix with .at for 8c , .at for 32F ... But what i need is a way to do it without doing a switch on the type of the Matrix. – Othman Benchekroun Jul 31 '14 at 08:12
  • Perhaps if you posted some code showing what you are currently doing ... – Bull Jul 31 '14 at 08:17
  • you can `.converTo` your Mat to a `float` Mat right in the beginning. – Micka Jul 31 '14 at 08:30
  • Well that's a good answer ! I'll try it – Othman Benchekroun Jul 31 '14 at 08:38
  • will give you some overhead, but should still be faster than your switch and typecast for each pixel ;) Alternative is to write your functions for each Mat type. – Micka Jul 31 '14 at 11:04

2 Answers2

2

This will do what you are asking, but obviously you would only want to call convertTo() once, not for every access.

Mat  dst;
image.convertTo(dst, CV_32F);
return dst.at<float>(i,j);
Bull
  • 11,771
  • 9
  • 42
  • 53
1

You should read the documentation:

  • The number of elements in a Mat is given by Mat::total()

  • The number of rows, columns and channels are given by Mat::rows, Mat::cols and Mat::channels(), respectively.

  • The type of data being held by the matrix is in type()

... and so on.

Read the documentation, and take a look to this tutorial on how to access matrix elements (unless you use C++11 type deduction or something equivalent).

EDIT:

there is no way of accessing a Mat of unknown type without putting a switch statement somewhere.

Яois
  • 3,838
  • 4
  • 28
  • 50
  • I think that my question was not clear, I know that i can access the elements of the Matrix with .at for 8c , .at for 32F ... But what i need is a way to do it without doing a switch on the type of the Matrix. – Othman Benchekroun Jul 31 '14 at 08:11
  • If your question is not clear, you can always edit ;) Take a look to that tutorial. – Яois Jul 31 '14 at 08:13