Discover Mat Matic Generic Generators

In OpenCV, it is common for accessing a pixel in a Mat object, for example:

 float b = A.at<float>(4,5); 

The problem is that if you do not know the apriori data type, you are stuck. Is there a way to write generic function headers that accept Mat with pattern type T ? I would like to build functions for computing linear algebra, and I don't want to have an if clause separating double and float . Something like:

  void func(Mat <T> a) { a.at<T>(3,4) = ... 

Is this possible in OpenCV?

+5
source share
3 answers

This is possible simply by templating your function:

 template<typename T> void func(Mat a) { a.at<T>(3,4) = ... 

But keep in mind that you don’t have an easy way to limit the type T to only double or floating, and your algorithm will probably not work on other types, but this may not be an actual problem.

Also note the disadvantages of using templates: What are the disadvantages of using templates?

+1
source

It seems another way to do this is to use a Mat_ object instead of Mat :

 template<typename T> void func(Mat_ <T> a) { cout << a(0,0) << endl; } 

If you want to pass Mat to func , you must specify a type:

 Mat a; func(Mat_<float>(a)); 

If you use a differnt type than the original Mat type, OpenCV will transform the conversion for you.

+3
source

The OpenCV 2 Cookbook page 40 claims that this is not possible. Also regarding Mat_:

"Using the at method in the cv :: Mat class can sometimes be cumbersome because the return type must be specified as a template argument for each call. In cases where the matrix type is known, you can use the cv :: Mat_ class, which is a subclass of the cv template :: Mat.

 cv::Mat_<uchar> im2= image; // im2 refers to image im2(50,100)= 0; //access to row 50 and column 100 

Since the type cv :: Mat_ elements are declared when a variable is created, the operator () method knows at compile time which type returns. "

EDIT : use Mat.type ()

 Mat image=imread("image.bmp"); cout<<image.type(); 

Console output:

 16 

Wiki: the method returns the type of the matrix element, an identifier compatible with a system of type CvMat, such as CV_16SC3 or a 16-bit signed 3-channel array, etc.

+1
source

All Articles