Qt+OpenCV 图像显示

Qt的图片数据类型QImage格式与OpenCV的Mat格式不一致,因此要实现转换,这通过下面的函数实现Mat到QImage的转换,打开文件对话框和显示图片的代码都在main函数中,下面是源代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 
#include 

using namespace cv;

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

    if (image.channels()==3) {
        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()==1) {
        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(0, "Open File", "", "*.jpg *.png *.bmp", 0);
    if (filename.isNull()) {
        return -1;
    }

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

    QLabel *label = new QLabel("", 0);
    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

你可能感兴趣的:(OpenCV)