c++opencvinitializationmatopencv-mat

How is the comma-separated initializer of OpenCV Mat implemented with C++?


#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main() {
    Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);

    cout << a << endl;

    return 0;
}

How is the comma-separated initializer of OpenCV Mat implemented with C++?

How does the "1" get into the Mat after the "0"?


Solution

  • To allow an initialization like

    Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);
    

    OpenCV first uses

    template <typename T>
    MatCommaInitializer_<T> operator<<(Mat_<T>&, T);
    

    to return an intermediate object MatCommaInitializer_<T>. This object has an overloaded operator,, namely

    template <typename T2>
    MatCommaInitializer_<T>& operator,(T2 v);
    

    which adds the value to the initializer. Then there is a constructor

    template <typename T>
    explicit Mat(MatCommaInitializer_<T> const&);
    

    to create a Mat object from a MatCommaInitializer.

    Note: You can find such information in the OpenCV documentation http://docs.opencv.org/master/ (http://docs.opencv.org/master/d6/d9e/classcv_1_1MatCommaInitializer__.html).