Instead of using imread() to read a file, how to I embed the image to be read in the source code itself? For example GIMP has an option to export an image as a C source or header file. How do I make use of that?
Asked
Active
Viewed 982 times
2 Answers
1
An image is just an array of numbers. OpenCV's Mat
constructor can accept a pointer to data:
Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
If your image data is a hard-coded array, you can can use it for initializing a cv::Mat
object

Rosa Gronchi
- 1,828
- 15
- 25
0
You can use this code snippet:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
// uncomment for test
//#include "image.h"
int main(int argc, char **argv)
{
Mat img=imread("D:\\ImagesForTest\\lena.jpg");
int w=img.cols;
int h=img.rows;
int channels=img.channels();
ofstream os("image.h");
os << "int rows=" << h << ";" << endl;
os << "int cols=" << w << ";" << endl;
os << "unsigned char d[]={" << endl;
for(int i=0;i<h;++i)
{
for(int j=0;j<w;++j)
{
if(i!=(w-1) || j!=(h-1))
{
Vec3b b=img.at<Vec3b>(i,j);
os << format("0x%02x,",b[0]);
os << format("0x%02x,",b[1]);
os << format("0x%02x,",b[2]);
}
}
}
Vec3b b=img.at<Vec3b>(w-1,h-1);
os << format("0x%02x,",b[0]);
os << format("0x%02x,",b[1]);
os << format("0x%02x",b[2]);
os << endl << "};" << endl;
os << "Mat I=Mat(rows,cols,CV_8UC3,d);" << endl;
os.close();
// uncomment for test
/*
namedWindow("I");
imshow("I",I);
waitKey();
return 0;
*/
}
it creates header file image.h that contains an image I.
It assumes that image is color 3 channel image with uchar element type.

Andrey Smorodov
- 10,649
- 2
- 35
- 42