-2

As per cv::Mat Class Reference, one of the constructor is:

    Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)

Now, I have rs2::frame and I want to convert them to cv::Mat. So, I have defined one function, and in the conversion, I want to specify the cv::Mat::type i.e. whether the output cv::Mat should be of type CV_8SC1 or CV_16SC1 or so on.

As of now, my function is something like this:

cv::Mat foo(rs2::frame fr, std::string mat_type) {
    .
    .
    .
}

For the mat_type, as shown above, I'm passing the string i.e. "CV_8SC1", "CV_16SC1", etc and in the function body, I'm manually comparing the strings:

    .
    .
    if(mat_type == "CV_8SC1") {
        return cv::Mat(width, height, CV_8SC1, ...);
    } else if ...
    .
    .
    .
    else {
        
    }

However, this is not very efficient, right? Let say, in the future, if I need another type of cv::Mat then I have to update the function by adding a new condition to if... else... statements.

So, how can I avoid this and do something else which is more efficient? I mean, is there any way to pass the cv::Mat::type directly rather than passing an equivalent string(s) and then comparing in the function body?

Just to clarify in advance: my question is different from these questions:

  1. What is the best practise for passing cv::Mats around - link
  2. How to Pass a cv::Mat across a network? - link
Milan
  • 1,743
  • 2
  • 13
  • 36

2 Answers2

0

Notice that the types are defined like this:

#define     CV_16S   3

I think you should pass an int (or uint64_t as in OpenCV's source code):

yourFunction(rs2::frame fr, int mat_type)

And call the and call your function like:

yourFunction(fr, cv::CV_8SC1)

you can see the definitions here , and there's a cool easy to use matrix here

Then, in your function do a switch case:

switch(mat_type) {
    case cv::CV_8SC1 : //Something
    case cv::CV_32S : //Something else
.
.
.

}

Anyway you will have to do a case for every type ( which is normal). And don't forget the necesary includes to access cv wherever you use it

Ivan
  • 1,352
  • 2
  • 13
  • 31
0

If your question is "Don't you think runtime type-checking is a bit impractical and doesn't scale well when you handle more and more types?" then the answer is yes, but that's what you sign for when you use type-erased objects like cv::Mat.

FYI there's a cv::Mat_<T> type in OpenCV that you can use in case you know the data type at compile-time and don't want to lose that information.

m88
  • 1,968
  • 6
  • 14