2017-08-16 176 views
0

我正在尝试编写一个函数,它将灰度OpenCv Mat放入Qt QPixmap,然后放入QLabel。C + + opencv垫到QPixmap错误

工作时间的三分之一。

第三时,它歪斜图像...

enter image description here

变得

enter image description here

上fromImage

的其余时间,程序崩溃,具体地()线。

我知道传入的Mat对象在每种情况下都是灰度和非空值。这是有问题的代码...

void MainWindow::updateCanvasLabel(Mat mat){ 

    imwrite("c:/pics/last-opened.jpg", mat); //to verify that Mat is 
              // what I think it is 

    QPixmap pixmap = QPixmap::fromImage(QImage((unsigned char*) mat.data, 
           mat.cols, 
           mat.rows, 
           QImage::Format_Grayscale8)); 

    ui->canvasLabel->setPixmap(pixmap); 
    ui->canvasLabel->setScaledContents(true); 
} 
+0

你可以上传图片,以及如何多渠道你有 – eyllanesc

+0

你可能有一些问题与渠道(RGB /灰度/ RGBA等)检查 –

回答

1

下面是什么我通常使用转换cv::MatQPixmapQImage

void MainWindow::updateCanvasLabel(Mat mat){ 

    QPixmap pixmap; 
    if(mat.type()==CV_8UC1) 
    { 
     // Set the color table (used to translate colour indexes to qRgb values) 
     QVector<QRgb> colorTable; 
     for (int i=0; i<256; i++) 
      colorTable.push_back(qRgb(i,i,i)); 
     // Copy input Mat 
     const uchar *qImageBuffer = (const uchar*)mat.data; 
     // Create QImage with same dimensions as input Mat 
     QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8); 
     img.setColorTable(colorTable); 
     pixmap = QPixmap::fromImage(img); 
    } 
    // 8-bits unsigned, NO. OF CHANNELS=3 
    if(mat.type()==CV_8UC3) 
    { 
     // Copy input Mat 
     const uchar *qImageBuffer = (const uchar*)mat.data; 
     // Create QImage with same dimensions as input Mat 
     QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888); 
     pixmap = QPixmap::fromImage(img.rgbSwapped()); 
    } 
    else 
    { 
     qDebug() << "ERROR: Mat could not be converted to QImage or QPixmap."; 
     return; 
    } 

    ui->canvasLabel->setPixmap(pixmap); 
    ui->canvasLabel->setScaledContents(true); 
}