【Qt】格式转换:QImage 转 OpenCV Mat

Qt5 中 QImage 转 OpenCV Mat 格式函数。

cv::Mat ImageMark::QImage2Mat(const QImage& image)
{
    switch(image.format())
    {
        // 8-bit, 4 channel
        case QImage::Format_ARGB32:
            break;
    	case QImage::Format_ARGB32_Premultiplied:
            {
                cv::Mat mat(image.height(), image.width(), 
                            CV_8UC4, 
                            (void*)image.constBits(), 
                            image.bytesPerLine());
                return mat.clone(); 
            }
            
        // 8-bit, 3 channel
        case QImage::Format_RGB32:
            {
            	cv::Mat mat(image.height(),image.width(),
                            CV_8UC4,
                            (void*)image.constBits(), 
                            image.bytesPerLine());
                
                 // drop the all-white alpha channel
                cv::cvtColor(mat, mat, cv::COLOR_BGRA2BGR);  
                return mat.clone();
            }
    	case QImage::Format_RGB888:
            {
                QImage swapped = inImage.rgbSwapped();
                cv::Mat mat(swapped.height(), swapped.width(), 
                            CV_8UC3,
                            (void*)image.constBits(), 
                            image.bytesPerLine());
                return mat.clone();
            }
            
        // 8-bit, 1 channel   
        case QImage::Format_Indexed8:
            {
                cv::Mat mat(image.height(),image.width(), 
                            CV_8UC1, 
                            (void*)image.constBits(), 
                            image.bytesPerLine());
                return mat.clone();
            }
            
        // wrong
        default:
            qDebug() << "ERROR: QImage could not be converted to Mat.";    
            break;
    }
    return cv::Mat();
}

 

你可能感兴趣的:(OpenCV,Qt,Qt,QImage,OpenCV,Mat,转换)