0

I have printed a cv::Mat object to a file using std::ofstream simply by writing ofs << mat;. When I try to do the same with std::ifstream, I get the following error:

binary '>>': no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion)

I know that overloading operators are possible and useful in many cases, like printing std::vector.

How can I overload operator >> such that it reads cv::Mat from an std::ifstream object like ifs >> mat?

Example result from std::cout << mat:

[253, 104;
 287, 222;
 282, 225;
 283, 225]
Burak
  • 2,251
  • 1
  • 16
  • 33
  • [Fast and efficient method in binary mode](https://stackoverflow.com/questions/32332920/efficiently-load-a-large-mat-into-memory-in-opencv/32357875#32357875) – Burak Apr 22 '21 at 13:08

1 Answers1

0
// read data to cv::Mat of type CV_64F
std::istream& operator >> (std::istream& is, cv::Mat& mat)
{
    char ch = 0;
    while (is.good() && ch != '[') {
        is >> ch;
    }
    //assert(ch == '[');
    std::vector<double> m(0);
    size_t cols = 0;
    bool end_of_file = false;
    while ( is.good() && ! end_of_file )
    {
        bool end_of_line = false;
        std::vector<double> v(0);
        while ( is.good() && ! end_of_line )
        {
            double d;
            is >> d;
            v.push_back(d);
            char c;
            is >> c;
            switch (c)
            {
            case ']':
                end_of_file = true;
            case ';':
                end_of_line = true;
                break;
            case ',':
                break;
            default:
                //std::cerr << "Unexpected character read: " << c << std::endl;
                //assert(c == ',');
            }
        }
        if (m.size() == 0) {
            cols = v.size();
        }
        else {
            //assert(v.size() == cols);
        }
        m.insert(m.end(), v.begin(), v.end());
    }
    cv::Mat res(cv::Size(cols, m.size() / cols), CV_64F, m.data());
    mat = res.clone();
    return is;
}

Note that it is based on assumptions about the input. The assertions are commented out for exception-safety.

Burak
  • 2,251
  • 1
  • 16
  • 33