4

Is there any way to store an OpenCv image histogram to disk so it can be loaded directly without being forced to load the image again and computing the histogram from it?

Thank you.

1 Answer 1

11

Assuming you are working on single channel (gray scale) image, the histogram can be represent by a single channel row matrix which length is equal to the number of bins in your histogram. Then you can easily load/save your histogram from/to a text file. If you want to use c++ opencv api, filestorage structure is also provide. Read this.

Here is a simple example:

// save file
cv::Mat my_histogram;
cv::FileStorage fs("my_histogram_file.yml", cv::FileStorage::WRITE);
if (!fs.isOpened()) {std::cout << "unable to open file storage!" << std::endl; return;}
fs << "my_histogram" << my_histogram;
fs.release();

// load file
cv::Mat my_histogram;
cv::FileStorage fs("my_histogram_file.yml", cv::FileStorage::READ);
if (!fs.isOpened()) {std::cout << "unable to open file storage!" << std::endl; return;}
fs >> "my_histogram" >> my_histogram;
fs.release();
4
  • Nice, thanks! I need the data into a cvHistogram to perform comparisons with it. I assume calling cv::createHist() and passing it the loaded cv::Mat will work, right? Commented Apr 23, 2012 at 10:59
  • double compareHist(InputArray H1, InputArray H2, int method) -- InputArray could be your loaded cv::Mat.
    – Eric
    Commented Apr 23, 2012 at 12:01
  • IsOpen() is depreciated. Use if( !fs.isOpened() ){ instead.
    – TimZaman
    Commented Oct 24, 2013 at 21:09
  • I got an error when I tried to read it as fs >> "my_histogram" >> my_histogram; I had to change it to: fs["my_histogram"] >> my_histogram; ref: docs.opencv.org/modules/core/doc/xml_yaml_persistence.html
    – rdasxy
    Commented Mar 28, 2014 at 18:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.