编程语言之类型之间转换

1. QString转换String

string s = qstr.toStdString();

2.String转换QString

QString qstr2 = QString::fromStdString(s);

3.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);
        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();
    }
}

4. QImage转Mat

Mat QImage2cvMat(QImage image)                          
{
    
    
    Mat mat;
    switch (image.format())
    {
    
    
    case QImage::Format_ARGB32:
    case QImage::Format_RGB32:
    case QImage::Format_ARGB32_Premultiplied:
        mat = Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
        break;
    case QImage::Format_RGB888:
        mat = Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
        cv::cvtColor(mat, mat, CV_BGR2RGB);
        break;
    case QImage::Format_Indexed8:
        mat = Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
        break;
    }
    return mat;
}

5.QImage与QPixmap互转

    QPainter p(this);
    QPixmap pixmap;
    pixmap.load("../image/路飞.jpg");
 
    //QPixmap->QImage
    QImage tempImage = pixmap.toImage();
    p.drawImage(0,0,tempImage);
 
    QImage image;
    image.load("../image/路飞.jpg");
 
    //QImage->QPixmap
    QPixmap tempPixmap = QPixmap::fromImage(image);
    p.drawPixmap(450,0,tempPixmap);

猜你喜欢

转载自blog.csdn.net/a8039974/article/details/105010836