Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access/modify matrix element in OpenCV? Why at() is templatized?

Should I know Mat element type for use at() correctly? For example, if I have

Mat rose = Mat(1,180, CV_64F, 0);

then can I call

rose.at<short>(i,j)++;

If not then which template argument should I use?

Why Mat::at is templatized while Mat itself is not?

UPDATE

This question contained sample code with another error, which is now here: How to fill Matrix with zeros in OpenCV?

like image 633
Suzan Cioc Avatar asked Jun 11 '13 08:06

Suzan Cioc


1 Answers

As already properly pointed out by William, you should provide only the correct type as a template argument for at. I believe that cv::Mat itself is not made template only for simplification. However, OpenCV crew are trying to support C++ features, including templates. The interface became slightly heterogeneous in this way.

You could not deduce compiler type from a type variable at runtime for obvious reason. However, you can deduce it at compile time, if your type variable is known at this point, using a traits class:

template<int I>
struct CvType {};

template<>
struct CvType<CV_64F> { typedef double type_t; };
template<>
struct CvType<CV_32F> { typedef float type_t; };
template<>
struct CvType<CV_8U> { typedef unsigned char type_t; };
// Other types go here

void main()
{
  const int type = CV_64F;
  cv::Mat mat(10, 10, type);
  mat.at<CvType<type>::type_t>(1, 1);
}

In this case you can change the value of type and wouldn't need to change types manually for all the at or other methods calls.

like image 194
Mikhail Avatar answered Oct 25 '22 05:10

Mikhail