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?
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;
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}