Ask Your Question
0

Mat to QImage

asked 2017-12-19 07:02:00 -0500

cjacquel gravatar image

Hello,

How to convert from a Mat object to a QImage in QT, and QImage to Mat ?

Thank you, Christophe,

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2017-12-19 10:59:34 -0500

kbarni gravatar image

Here is a function to convert Mat to QPixmap or QImage. It's much faster than the direct pixel access using the Mat::at(y,x) function:

QPixmap MatToPixmap(cv::Mat src)
{
    QImage::Format format=QImage::Format_Grayscale8;
    int bpp=src.channels();
    if(bpp==3)format=QImage::Format_RGB888;
    QImage img(src.cols,src.rows,format);
    uchar *sptr,*dptr;
    int linesize=src.cols*bpp;
    for(int y=0;y<src.rows;y++){
        sptr=src.ptr(y);
        dptr=img.scanLine(y);
        memcpy(dptr,sptr,linesize);
    }
    if(bpp==3)return QPixmap::fromImage(img.rgbSwapped());
    return QPixmap::fromImage(img);
}

To convert a QImage to Mat, invert the parameters of the memcpy function.

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2017-12-19 07:02:00 -0500

Seen: 629 times

Last updated: Dec 19 '17