c++ OpenCV : Convert mat to base64 and vice versa

14,935

Solution 1

There you go! (C++11)
Encode img -> jpg -> base64 :

        std::vector<uchar> buf;
        cv::imencode(".jpg", img, buf);
        auto *enc_msg = reinterpret_cast<unsigned char*>(buf.data());
        std::string encoded = base64_encode(enc_msg, buf.size());

Decode base64 -> jpg -> img :

        string dec_jpg =  base64_decode(encoded);
        std::vector<uchar> data(dec_jpg.begin(), dec_jpg.end());
        cv::Mat img = cv::imdecode(cv::Mat(data), 1);

Note that you can change JPEG compression quality by setting the IMWRITE_JPEG_QUALITY flag.

Solution 2

I'm encountering nearly the same problem, but I'm trying to encode a Mat into jpeg format and then convert it into base64.

The code on that page works fine!

So here is my code:

VideoCapture cam(0);
cam>>img;
vector<uchar> buf;
imencode(".jpg", img, buf);
uchar *enc_msg = new uchar[buf.size()];
for(int i=0; i < buf.size(); i++) enc_msg[i] = buf[i];
string encoded = base64_encode(enc_msg, buf.size());

if you just want to convert a Mat into base64, you need make sure the Mat size and channels. For a CV_8UC1, this will work:

string encoded = base64_encode(img.data, img.rows * img.cols);

Solution 3

I have created an example for this using Qt5 and OpenCV:

cv::Mat1b image;
this->cameraList[i]->getImage(image);
std::vector<uint8_t> buffer;
cv::imencode(".png", image, buffer);
QByteArray byteArray = QByteArray::fromRawData((const char*)buffer.data(), buffer.size());
QString base64Image(byteArray.toBase64());
base64ImageList.append(base64Image);
Share:
14,935

Related videos on Youtube

Amarnath R
Author by

Amarnath R

Nothing

Updated on July 26, 2022

Comments

Related