When using OpenCV to develop programs, it is difficult to view matrix data, while matlab is very convenient to view data. One method is hybrid programming of matlab and c ++, you can use matlab to access the c ++ memory. Unfortunately, I will not use this method, so I will write the data into the file, read it using matlab, and then use various advanced functions of matlab to view the data value.
1. Write Mat data to a specified file
To facilitate the reader, I directly paste this function. You just need to copy the code to your own code and use it directly. If you have any questions, please comment. I will check the problem as soon as possible.
#include
#include
#include
#include
using namespace std;using namespace cv;int abWrite(const Mat &im, const string &fname){ ofstream ouF; ouF.open(fname.c_str(), std::ofstream::binary); if (!ouF) { cerr << "failed to open the file : " << fname << endl; return 0; } for (int r = 0; r < im.rows; r++) { ouF.write(reinterpret_cast
(im.ptr(r)), im.cols*im.elemSize()); } ouF.close(); return 1;}
2. Use matlab to read data from binary files
When using matlab to read data, you must know the Mat width, height, number of channels, and types of individual channel elements!
Take the three-channel, UCHAR as an example to read data and display data.
C ++ program, used to call the abWrite function.
Mat orgIm = imread("im.jpeg");abWrite(orgIm, "./orgIm_8UC3.dat");
The Matlab program reads orgIm_8UC3.dat data and adjusts it to RGB data display.
Width = 321; % specify the width of your matrix, height = 481; % specify the height of your matrix, channels = 3; % channel count fs = fopen ('orgim _ 8UC3. dat ', 'rb'); db = fread (fs, 'uint8'); % Note: Here unsigned int8fclose (fs); ou = reshape (db, channels * height, width); % adjust the display format im (:,:, 1) = ou (3: 3: end, :) '; % R channel im (:,:, 2) = ou (2: 3: end, :) '; % G channel im (:,:, 3) = ou (1: 3: end ,:)'; % B channel figure; imshow (uint8 (im) % Be sure to convert to uint8
My used test images:
Display image after matlab execution: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48cD48aW1nIHNyYz0 = "http://www.2cto.com/uploadfile/Collfiles/20140613/20140613092026220.png" alt = ""/>
This experiment shows that abWrite is very likely to be okay. If you want to test it, write a code to test it. If you have any questions about the test, please comment. I will solve the problem as soon as possible.