How to print cv :: Mat in any CSV, C, Python, MatLab, NumPy format
In addition to creating cv::Formatter
explicitly, one can also use cv::format()
which can be used with std::cout
directly, and is a little shorter:
cv::Mat image; //Loaded from somewhere
std::cout << cv::format(image, "numpy") << std::endl;
If the second argument cv::format()
is any string specified by brotherofken , then answer.
In version 3 of OpenCV, it format()
no longer takes a string, but an enumeration. The enumeration constants correspond to valid string values and are as follows:
FMT_DEFAULT
FMT_MATLAB
FMT_CSV
FMT_PYTHON
FMT_NUMPY
FMT_C
The call is similar to above:
std::cout << cv::format(image, cv::Formatter::FMT_NUMPY) << std::endl;
source to share
For these purposes, you can use an undocumented class cv::Formatter
. 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);
After use, do not destroy the cv::Formatter
object derived from cv::Formatter::get(...)
.
The function cv::Formatter::get(const char* fmt)
can work with the following formats:
"MATLAB"
Output example:
[120, 195, 226;
142, 138, 78;
195, 142, 226]
"CSV" is a 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" - creates a c-style array
Output example:
{120, 195, 226, 142, 138, 78, 195, 142, 226}
source to share