cvmat qimage互转

作者:fly 发布于:2016-12-21 15:36 分类:Linux

如果转换出现问题,请查阅调试信息。有时ARGB32与RGB32格式搞错会导致没有图像输出的。


cv::Mat MainWindow::QImage2cvMat(QImage *image)
{
    cv::Mat mat;
    switch(image->format())
    {
        case QImage::Format_ARGB32:
            printf("-ARGB32");
        case QImage::Format_RGB32:
            printf("-RGB32");
        case QImage::Format_ARGB32_Premultiplied:
             printf("-ARGB32_Premu");
            mat = cv::Mat(image->height(), image->width(), CV_8UC4, (void*)image->constBits(), image->bytesPerLine());
            break;
        case QImage::Format_RGB888:
             printf("-888");
            mat = cv::Mat(image->height(), image->width(), CV_8UC3, (void*)image->constBits(), image->bytesPerLine());
            cv::cvtColor(mat, mat, CV_BGR2RGB);
            break;
        case QImage::Format_Indexed8:
            printf("-index8");
            mat = cv::Mat(image->height(), image->width(), CV_8UC1, (void*)image->constBits(), image->bytesPerLine());
            break;
           default: printf("-other");break;
        }
        return mat;
}
QImage MainWindow::cvMat2QImage(const cv::Mat mat)
{
    if(mat.type() == CV_8UC1)
    {
        printf("-8uc1");
        QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
        image.setColorCount(256);
        for(int i = 0; i < 256; i++)
        {
            image.setColor(i, qRgb(i, i, i));
        }
        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;
    }
    else if(mat.type() == CV_8UC3)
    {
         printf("-8uc3");
        const uchar *pSrc = (const uchar*)mat.data;
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return image.rgbSwapped();
    }
    else if(mat.type() == CV_8UC4)
    {
         printf("-8uc4");
        const uchar *pSrc = (const uchar*)mat.data;
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB32);
        return image.copy();
    }
    else
    {
         printf("-other");
        return QImage();
    }
}


发表评论:

 
Powered by emlog sitemap