QImage to OpenCV

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

QImage to OpenCV

gijzelaerrr
hi Everyone,

As many people before I'm using OpenCV and Qt. I've managed to convert a
OpenCV c++ Mat into an Qimage using a shared memory method:

    cvtColor(mat_bgr, mat_rgb, CV_BGR2RGB);
    qframe = QImage((const unsigned char*)(mat_rgb.data), mat_rgb.cols,
        mat_rgb.rows, QImage::Format_RGB888);

but when i try to do the same the other way it works (no error) but the
image is distorted, it looks like the channels are mixed up:

    Mat mat(qimage.height(), qimage.width(), CV_8UC3,
        (uchar*)qimage.bits(), qimage.bytesPerLine());
    cvtColor(mat, mat2, CV_BGR2RGB);

I've been looking on the internet for people trying to do the same, but
most people just convert from OpenCV to Qt as purpose to display, I want
to do it the other way around. Anybody an idea, suggestion or anything?

thanks,

Gijs Molenaar
http://gijs.pythonic.nl
Reply | Threaded
Open this post in threaded view
|

Re: QImage to OpenCV

gijzelaerrr

I found out what is wrong, QImage has a forth channel for alpha. When you read the qimage data into a 4 channel mat and remove the fourth channel everything is okay. The weird thing is that somehow the QIMage seems to be in BGRA order, but maybe I'm doing something wrong.

Mat qimage2mat(const QImage& qimage) {
    cv::Mat mat = cv::Mat(qimage.height(), qimage.width(), CV_8UC4, (uchar*)qimage.bits(), qimage.bytesPerLine());
    cv::Mat mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3 );
    int from_to[] = { 0,0,  1,1,  2,2 };
    cv::mixChannels( &mat, 1, &mat2, 1, from_to, 3 );
    return mat2;
};

QImage mat2qimage(const Mat& mat) {
    Mat rgb;
    cvtColor(mat, rgb, CV_BGR2RGB);
    return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888);
};


--- In [hidden email], Gijs Molenaar <gijsmolenaar@...> wrote:

>
> hi Everyone,
>
> As many people before I'm using OpenCV and Qt. I've managed to convert a
> OpenCV c++ Mat into an Qimage using a shared memory method:
>
>     cvtColor(mat_bgr, mat_rgb, CV_BGR2RGB);
>     qframe = QImage((const unsigned char*)(mat_rgb.data), mat_rgb.cols,
> mat_rgb.rows, QImage::Format_RGB888);
>
> but when i try to do the same the other way it works (no error) but the
> image is distorted, it looks like the channels are mixed up:
>
>     Mat mat(qimage.height(), qimage.width(), CV_8UC3,
>         (uchar*)qimage.bits(), qimage.bytesPerLine());
>     cvtColor(mat, mat2, CV_BGR2RGB);
>
> I've been looking on the internet for people trying to do the same, but
> most people just convert from OpenCV to Qt as purpose to display, I want
> to do it the other way around. Anybody an idea, suggestion or anything?
>
> thanks,
>
> Gijs Molenaar
> http://gijs.pythonic.nl
>