天天看點

Qt+OpenCV 圖像顯示

Qt的圖檔資料類型QImage格式與OpenCV的Mat格式不一緻,是以要實作轉換,這通過下面的函數實作Mat到QImage的轉換,打開檔案對話框和顯示圖檔的代碼都在main函數中,下面是源代碼:

#include <QApplication>
#include <QWidget>
#include <QImage>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>

#include <cv.h>
#include <highgui.h>

using namespace cv;

static QImage Mat2QImage(Mat& image)
{
    QImage img;

    if (image.channels()==) {
        cvtColor(image, image, CV_BGR2RGB);
        img = QImage((const unsigned char *)(image.data), image.cols, image.rows,
                image.cols*image.channels(), QImage::Format_RGB888);
    } else if (image.channels()==) {
        img = QImage((const unsigned char *)(image.data), image.cols, image.rows,
                image.cols*image.channels(), QImage::Format_ARGB32);
    } else {
        img = QImage((const unsigned char *)(image.data), image.cols, image.rows,
                image.cols*image.channels(), QImage::Format_RGB888);
    }

    return img;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget *wn = new QWidget;
    wn->setWindowTitle("disp image");

    QString filename = QFileDialog::getOpenFileName(, "Open File", "", "*.jpg *.png *.bmp", );
    if (filename.isNull()) {
        return -;
    }

    Mat image = imread(filename.toAscii().data(), );
    QImage img = Mat2QImage(image); 

    QLabel *label = new QLabel("", );
    label->setPixmap(QPixmap::fromImage(img));

    QPushButton *bnt = new QPushButton("Quit");
    QObject::connect(bnt, SIGNAL(clicked()), &app, SLOT(quit()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(label);
    layout->addWidget(bnt);
    wn->setLayout(layout);

    wn->show();

    return app.exec();
}
           

// 設定圖像的大小為QLabel的大小

ui->labelimage->setPixmap(QPixmap::fromImage(myImage).scaled(ui->labelimage->size()));
           

【轉自:】

  1. http://blog.csdn.net/xiahouzuoxin/article/details/41692891
  2. http://blog.csdn.net/yang6464158/article/details/38109415