Qt中OpenCV Mat与QImage、QPixmap和QImage的相互转换

1、QPixmap转为Image:

QPixmap pixmap;
pixmap.load("../Image/1.jpg");
QImage tempImage = pixmap.toImage();

2、QImage转为QPixmap:

QImage image;
image.load("../Image/1.jpg");
QPixmap tempPixmap = QPixmap::fromImage(image);

3、QImage转换成Mat

 1 Mat QImage2cvMat(QImage image)
 2 {
 3     cv::Mat mat;
 4     switch(image.format())
 5     {
 6     case QImage::Format_ARGB32:
 7     case QImage::Format_RGB32:
 8     case QImage::Format_ARGB32_Premultiplied:
 9         mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.bits(), image.bytesPerLine());
10         break;
11     case QImage::Format_RGB888:
12         mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.bits(), image.bytesPerLine());
13         cv::cvtColor(mat, mat, CV_BGR2RGB);
14         break;
15     case QImage::Format_Indexed8:
16         mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.bits(), image.bytesPerLine());
17         break;
18     }
19     return mat;
20 }

4、Mat转换成QImage

QImage cvMat2QImage(const cv::Mat& mat)
{
    // 8-bits unsigned, NO. OF CHANNELS = 1
    if(mat.type() == CV_8UC1)
    {
        QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
        // Set the color table (used to translate colour indexes to qRgb values)
        image.setNumColors(256); //5.9版本之后取消了setNumColors函数,可以使用image.setColoeCount(256);
        for(int i = 0; i < 256; i++)
        {
            image.setColor(i, qRgb(i, i, i));
        }
        // Copy input Mat
        uchar *pSrc = mat.data;
        for(int row = 0; row < mat.rows; row ++)
        {
            uchar *pDest = image.scanLine(row);
            memcpy(pDest, pSrc, mat.cols);
            pSrc += mat.step;
        }
        return image;
    }
    // 8-bits unsigned, NO. OF CHANNELS = 3
    else if(mat.type() == CV_8UC3)
    {
        // Copy input Mat
        const uchar *pSrc = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return image.rgbSwapped();
    }
    else if(mat.type() == CV_8UC4)
    {
        // Copy input Mat
        const uchar *pSrc = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
        return image.copy();
    }
    else
    {
        return QImage();
    }
}

你可能感兴趣的:(opencv,iot,gbk,loadrunner,shader)