1

I'm trying to save an OpenCV mat containing image pixels to a txt file (that will be imported to a VHDL testbench afterwards for further processing).

I need the file to contain only pixel values without any other information and I need it to be in hexadecimal. Also without any separators such as commas, semicolons, etc..

what I came up with up till now is:

cv::Mat srcImage;
srcImage = imread("image.jpg", 1);
if (srcImage.empty())
{
    cout << "ERROR : Image cannot be loaded..!!" << endl;
    return -1;
}

cv::FileStorage file("data.txt", cv::FileStorage::WRITE); file <<"srcImage"<<srcImage;

The output text file contains all the stuff which I don't need. I tried all the combinations in order to write the hex values but failed...

Can anyone help, please?

Thanks

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
R.T
  • 25
  • 6

2 Answers2

0

In case you image is gray ('one channel 8 bit depth')

for (int y=0; y< srcImage.rows; ++y) {
    for (int x=0; x < srcImage.cols; ++x) {
        file << srcImage .at<uchar>(y,x);}}

else change the data type for the "at" function to Vec3b if 3 channel

Miki
  • 40,887
  • 13
  • 123
  • 202
M.Sabaa
  • 319
  • 2
  • 8
  • @M.Sebaa thanks for the response, the image is 24bit rgb, but i need the output to be in hex value not uchar, do you have any idea how to to it? – R.T Feb 06 '17 at 14:36
  • file << std::hex << (int) srcImage .at(y,x); – M.Sabaa Feb 06 '17 at 14:45
  • @Miki well, I tried researching since all morning. std::hex does not work with cv::Filestorage i tried that already, and thats why I posted the question. All the answers I found, use the normal file stream method. My question is how to do that with openCV cv::Filestorage as stated in my example above. – R.T Feb 06 '17 at 16:29
  • @M.Sabaa you suggestion `file << std::hex << (int) srcImage .at(y,x);` is not working. It gives me: "no matching function for call to 'write'." – R.T Feb 06 '17 at 16:35
  • @R.T I'm sorry, I read this answer too quickly. This can't work. I'll post a new answer – Miki Feb 06 '17 at 16:36
0

You can't do this using a cv::FileStorage. You can just save the data as you need to a file using std::ofstream:

#include <opencv2\opencv.hpp>
#include <iostream>
#include <iomanip>
using namespace std;
using namespace cv;

int main()
{
    Mat3b img(3, 4, Vec3b(15,14,12));
    randu(img, Scalar(0, 0, 0), Scalar(256, 256, 256));

    // Save to Hex ASCII
    ofstream out("data.txt");
    for (int r = 0; r < img.rows; ++r) {
        for (int c = 0; c < img.cols; ++c) {
            const Vec3b& v = img(r, c);
            out << hex << uppercase << setw(2) << setfill('0') << int(v[0]);
            out << hex << uppercase << setw(2) << setfill('0') << int(v[1]);
            out << hex << uppercase << setw(2) << setfill('0') << int(v[2]);
        }
    }

    return 0;
}
Miki
  • 40,887
  • 13
  • 123
  • 202
  • Thanks @Miki, I guess I will be using your suggestion its working instead of FileStorage. – R.T Feb 20 '17 at 09:46