TGuerin
TGuerin

Reputation: 345

Opencv Mat conversion to QByteArray

I need to transfer image from my Qt application (with OpenCv) to my web application through websocket. The transfer with binary data works great. I have a test web app which sends an image to my Qt app and the image (QbyteArray) is directly re-sends to my web app. That's work.

My problem now, is to receive my QByteArray, convert it to Mat image. Or convert my Mat array to QbyteArray in order to send it.

So I tried to convert QByteArray to Mat :

Mat imgbuf = Mat(200, 200, CV_8UC3, message.data);
Mat matImg = imdecode(imgbuf, CV_LOAD_IMAGE_ANYCOLOR);

Imgbuf is not empty but the imdecode method returns an empty Mat.

And I also tried to convert Mat to QbyteArray (the most important for me) :

cv::resize(img, img, Size(200, 200));
std::vector<float> array;
if (img.isContinuous()) {
    array.assign((float*)img.datastart, (float*)img.dataend);
}
else {
    for (int i = 0; i < img.rows; ++i) {
        array.insert(array.end(), (float*)img.ptr<uchar>(i),(float*)img.ptr<uchar>(i) + img.cols);
    }
}

QByteArray ImgByte((char*)array.data(), array.size());

server->sendBinary(ImgByte);

Here ImgByte isn't empty but I have nothing on my Html page...

Here the code for test web app :

function handleReceive(message) {
     // canvas    
     var c = resultCanvas = document.getElementById('result');  
     var ctx = c.getContext('2d');
     var imageData = ctx.createImageData(200, 200);
     var pixels = imageData.data;

     var buffer = new Uint8Array(message.data);
     for (var i=0; i < pixels.length; i++) {
          pixels[i] = buffer[i];
     }
     console.log(imageData);
     ctx.putImageData(imageData, 0, 0);
}

Upvotes: 2

Views: 3817

Answers (1)

TGuerin
TGuerin

Reputation: 345

I found the solution to convert Mat to QBytesarray and vice versa.

So, to send Mat image through Websocket :

Mat imgC4In;
resize(imgBufIn, imgBufIn, Size(200, 200));
cvtColor(imgBufIn, imgC4In, CV_BGR2BGRA); // Need to be BGRA to display in canvas (js client)

// Conversion from Mat to QByteArray
QByteArray ImgByteI((char*)(imgC4In.data), 160000);

server->sendBinary(ImgByteI);

Really simple and that works well !

To get Mat from QByteArray :

Mat img = Mat(200, 200, CV_8UC4, messageQByte.data());

Upvotes: 1

Related Questions