3

I have an OpenCV matrix. I want to print it formatted in any style as mentioned in the question.

cv::Mat1b image = cv::imread(input_name, cv::IMREAD_GRAYSCALE);
std::cout << format_in_c_style(image);

Any ideas?

2 Answers 2

6

In addition to creating a cv::Formatter explicitly, one can also use cv::format(), which can be used with std::cout directly, and is a little bit shorter:

cv::Mat image;    //Loaded from somewhere
std::cout << cv::format(image, "numpy") << std::endl;

Where the second argument to cv::format() is any of the strings mentioned in brotherofken's answer.

In OpenCV version 3, format() no longer takes a string, but an enumeration. The enumeration constants correspond to the allowed string values, and are as follows:

FMT_DEFAULT
FMT_MATLAB
FMT_CSV
FMT_PYTHON
FMT_NUMPY
FMT_C

The invocation is similar to above:

std::cout << cv::format(image, cv::Formatter::FMT_NUMPY) << std::endl;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I think it's more convinient way to print data.
6

You can use undocumented cv::Formatter class for this purposes. See example below:

cv::Mat1b const image = cv::imread(m_cl_parameters.input_name, cv::IMREAD_GRAYSCALE);

cv::Formatter const * c_formatter(cv::Formatter::get("CSV"));

c_formatter->write(std::cout, image);

You should not destroy cv::Formatter object obtained from cv::Formatter::get(...) after usage.

Function cv::Formatter::get(const char* fmt) can deal with following formats:

"MATLAB"

Output example:

[120, 195, 226;
 142, 138, 78;
 195, 142, 226]

"CSV" - comma-separated value.

Output example:

120, 195, 226
142, 138, 78
195, 142, 226

"PYTHON"

Output example:

[[120, 195, 226],
 [142, 138, 78],
 [195, 142, 226]]

"NUMPY"

Output example:

array([[120, 195, 226],
       [142, 138, 78],
       [195, 142, 226]], type='uint8')

"C" - produces c-style array

Output example:

{120, 195, 226, 142, 138, 78, 195, 142, 226}

2 Comments

Asked and answered at the same time by the same person ;-) Thanks for the hint btw.. +1
It is standard option on StackOverflow. There are "Answer your own question" checkbox below the "Post your question" button. It's just one of the ways to share knowledge. Thank you :-)

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.