Take the 2-minute tour ×

So I'm using the class Mat from opencv in a program I'm writing. Mat looks something like this:

class Mat {
        Mat(int width, int height, int type);
        template <typename T> T getElt(int x, int y);
        int depth();

The type in the constructor specifies whether elements in the Mat are floats, ints, etc as well as the number of channels in the image. depth() returns the data type used to store image elements.

Unfortunately I have to call getElt() in my code. Whenever I do that I use a switch statement to check the depth of the Mat so I can call getElt() with the appropriate template parameter. Doing it that way is pretty verbose, so I was wondering if there was a better way to do it. Could I create a container for a Mat and use template magic create a method that returns a type as opposed to a value? Or could I use macros to make things more efficient and logical?

I'd rather not have to subclass Mat since there are several methods besides getElt() for which I have this same issue.

Edit: made the description more accurate.

share|improve this question
What happens if you call it with the "wrong" template parameter? Do you get garbage or does the result get converted to the requested type? If the latter, could you possibly always use double type? –  zvrba Jul 16 '10 at 15:12
That would not work: the docs say the type must match the actual matrix type. –  amc Jul 16 '10 at 15:17
add comment

2 Answers

IIRC the 'type' in openCV MAT corresponds to the image type (ie number of channels) not the data type float/int/char etc.

If you want a templated image class that can transparently work with char/int/bool/double etc - take a look at CImg

share|improve this answer
Thanks for the recommendation, but I need to use other functionality provided by opencv that would be hard to write myself. –  amc Jul 16 '10 at 15:25
I thought so! Although CImg does have a lot of functionality - it's the best image lib if you need template image types. –  Martin Beckett Jul 16 '10 at 15:37
add comment

You're probably looking for Mat_<T> instead. An black&white image really isn't the same as a greyscale image, and neither is equal to a color image. Those should be separate at compile time.

share|improve this answer
add comment

Your Answer


