C++ – opencv binary data jpg image to cv::Mat

cimage processinglibpqxxopencvpostgresql

I want to load an image in c++ opencv that comes from a postgresql database.
The image, jpg extension, is stored as a binary data (bytea type) in the base, that I can access thanks to libpqxx.

The problem is that I do not know how to convert the data into a cv::Mat instance. With a regular image I could use imread('myImage.jpg', …), but in this case I cannot even load the database image in the data attribute of Mat because it is jpeg and not bmp.

Any idea ? Is there some opencv method I could use that could understand directly the binary data and convert it to the appropriate structure ? the imdecode() functions seems to be used for bitmap datas.

edit : Berak, using a vector the imdecode function returns null Matrice What happens "If the buffer is too short or contains invalid data, the empty matrix/image is returned." Here is the code :

pqxx::result r=bdd::requete("SELECT image FROM lrad.img WHERE id=3",1);//returns the bytea image in r[0]["image"]
const char* buffer=r[0]["image"].c_str();    
vector<uchar>::size_type size = strlen((const char*)buffer);
vector<uchar> jpgbytes(buffer, buffer+size);
Mat img = imdecode(jpgbytes, CV_LOAD_IMAGE_COLOR); 
//jpgbytes.size()=1416562 img.size()=[0 x 0]

What am I missing ?

Best Answer

still, use imdecode . it can handle png,jpg,bmp,ppm,webp,jp2,exr, but no gif.

vector<uchar> jpgbytes; // from your db
Mat img = imdecode(jpgbytes);

(you should do the same for bmp or any other supported formats, don't mess with Mat's raw data pointers!)

Related Topic