Search code examples
opencvstdmat

Accessing element of complex Mat in OpenCV


I need to access the real part specific element of a cv::Mat that contains std::complex<double>'s.

OpenCV provides codes of how to create a complex cv::Mat_ here (search the page for the keyword "complex" and the first mention of that word is where the example is).

Here is my attempt:

Mat B = Mat_<std::complex<double> >(3, 3);
cout << B.depth() << ", " << B.channels() << endl;
B.at<double>(0, 0) = 0;
cout << "B(0,0) = " << B.at<double>(0, 0).real(); // Error due to .rea()

Solution

  • The Mat is filled with the type std::complex<double> but you're requesting a double when you write B.at<double>(0, 0); the return type is double, which doesn't have a .real() method. Instead you need to return the complex type which your Mat holds:

    cout << "B(0,0) = " << B.at<std::complex<double> >(0, 0).real();
    

    B(0,0) = 0

    If you want to set an imaginary number, you'll need to actually pass that into the matrix, otherwise it just sets the real part:

    B.at<double>(0, 0) = 2;
    cout << "B(0,0) = " << B.at<std::complex<double> >(0, 0);
    

    B(0,0) = (2,0)

    B.at<std::complex<double> >(0, 0) = std::complex<double> (2, 1);
    cout << "B(0,0) = " << B.at<std::complex<double> >(0, 0);
    

    B(0,0) = (2,1)