The reason why the image is skewed when converting QImage to Mat

Generally, the conversion of Mat to QImage is like this

    Mat rgb;

    QImage img;
    if(mat.channels() == 3)    // RGB image
    {

        cvtColor(mat,rgb,CV_BGR2RGB);
        img = QImage((const uchar*)(rgb.data),  //(const unsigned char*)
                     rgb.cols,rgb.rows,
                     QImage::Format_RGB888);
    }else                     // gray image
    {
        img = QImage((const uchar*)(mat.data),
                     mat.cols,mat.rows,
                     QImage::Format_Indexed8);
    }

But if the width is not an integer multiple of 4, the image is skewed

Cause Analysis:

When QImage is converted to Format_RGB888 and other formats, each line will be aligned by 4 bytes (32 bits), and if it is insufficient, it will be automatically filled.

However, the data in rgb.data is not automatically filled, so it will cause the image to be skewed when it is displayed as a QImage

So the above code should be changed to the following

    Mat rgb;

    QImage img;
    if(mat.channels() == 3)    // RGB image
    {

        cvtColor(mat,rgb,CV_BGR2RGB);
        img = QImage((const uchar*)(rgb.data),  //(const unsigned char*)
                     rgb.cols,rgb.rows,
                     rgb.cols*rgb.channels(),   //new
                     QImage::Format_RGB888);
    }else                     // gray image
    {
        img = QImage((const uchar*)(mat.data),
                     mat.cols,mat.rows,
                     mat.cols*mat.channels(),  //new
                     QImage::Format_Indexed8);
    }

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326846451&siteId=291194637