3
float matrix_data[] = {0.9867, 0.02454, -0.1603,
                       0.01921, 0.9638, 0.2657,
                       0.16112, -0.2652, 0.9506};

cv::Mat res_mat = cv::Mat(3,3,CV_32F,matrix_data);
cout << "res_mat :" << res_mat<<endl;

I know I can see the output of the mat by this but I want to add this mat to a string, something like this:

std::string my_str = "my mat :";
my_str += to_String(res_mat);

so the desired result will be like :

my mat : 0.9867, 0.02454, -0.1603, 0.01921, 0.9638, 0.2657,0.16112, -0.2652, 0.9506

3 Answers 3

2

Use std::ostringstream. Before that, create new header for your matrix to treat it as vector:

cv::Mat oneRow = res_mat.reshape(0,1);    // Treat as vector 
std::ostringstream os;
os << oneRow;                             // Put to the stream
std::string asStr = os.str();             // Get string 
asStr.pop_back();                         // Remove brackets
asStr.erase(0,1);
cout << "res_mat :" << asStr <<endl;
Sign up to request clarification or add additional context in comments.

2 Comments

which opencv header defines operator<<() for ostream and Mat? Without including anything, this does not compile (in current opencv versions).
In my version it is contained by cvstd.inl.hpp
1

You may also reach every element of the Mat and adding the elements to a string type. This can be also used.

Here is the code:

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

using namespace cv;
using namespace std;

int main()
{

    float matrix_data[] = {0.9867, 0.02454, -0.1603,
                           0.01921, 0.9638, 0.2657,
                           0.16112, -0.2652, 0.9506};

    cv::Mat res_mat = cv::Mat(3,3,CV_32F,matrix_data);
    cout << "res_mat :" << res_mat<<endl;

    std::string my_str = "my mat :";

    for(int i=0; i<res_mat.rows; i++)
    {
       for(int j=0; j<res_mat.cols; j++)
       {
           my_str += to_string(res_mat.at<float>(i,j)) + ", ";
       }
    }

    cout<<my_str<<endl;

}

1 Comment

perfect this was what I was looking for
1

You can get a string representation by using String& operator << (String& out, const Mat& mtx)

float matrix_data[] = {0.9867, 0.02454, -0.1603,
                       0.01921, 0.9638, 0.2657,
                       0.16112, -0.2652, 0.9506};

cv::Mat res_mat = cv::Mat(3, 3, CV_32F, matrix_data);

std::string my_str = "my mat :";
my_str << res_mat;  // ← it's that simple

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.