Home > Software design >  How to make getting a pixel value independent of the cv::Mat type?
How to make getting a pixel value independent of the cv::Mat type?

Time:04-14

I am writing a method that uses OpenCV (C ). For example

void foo(const cv::Mat &image);

Inside, I need to take the pixel value of the cv::Mat by row and column.

If the type of image the method works with is CV_32FC3, I need to use

image.at<cv::Vec3f>(row, col);

If the type is CV_32SC2, I need to use

image.at<cv::Vec2i>(row, col);

If the type is CV_8UC1, I need to use

image.at<uchar>(row, col);

etc.

I would like the method to be universal, that is, it works with an image with any number of channels and depth. Can anything be done to fulfill this requirement (any template logic)? Perhaps the solution is quite obvious, but I did not find it.

Thank you!

CodePudding user response:

Drop the use of cv::Mat - where you have to call type() method (at runtime) to get the type of values stored by mat, and instead that just start using templated version of mat class: it is cv::Mat_<Type> and write more generic code.

Then you could write only one function template to read mat pixels:

template<class T>
T access(cv::Mat_<T> const& img, int r, int c) {
    return img(r,c);
}

More about cv::Mat_ here.

  • Related