Two methods of Qt+OpenCV displaying pictures (code demonstration)

guide

    This article mainly introduces two methods of displaying images by Qt+OpenCV, and demonstrates the effect through code.

background introduction

    OpenCV itself provides some GUI methods, but there are still limitations in using them. Taking C++ as an example, most of us will use Qt or MFC to write GUI programs in practical applications. In contrast, Qt is easier to use than MFC and has richer interface styles, so more and more C++ visual developers and companies tend to use Qt as the GUI of visual projects.

    There are two commonly used methods for displaying OpenCV images in Qt, one is to use QLabel to display, and the other is to use QGraphicsView to display.

picture

picture

Implementation steps

    First prepare the pictures to be displayed, configure the OpenCV environment (skip here), and create a new Qt Widgets application.

[1] Add a Label control and a Graphics View control, remove the Label text content, and add a border.

picture

[2] Add two Push Buttons (named QLabel and Graphics View respectively), and design the layout simply.

[3] Go to the slot function corresponding to Button and add code:

//QLabel显示OpenCV图像void MainWindow::on_pushButton_clicked(){
   
       Mat srcImg = imread("1.jpg");    if(srcImg.empty())    {
   
           QMessageBox::information(this,"警告","图片读取失败,请检查图片路径!");        return;    }    Mat imgShow;    cvtColor(srcImg, imgShow, COLOR_BGR2RGB); // 图像格式转换    QImage qImg = QImage((unsigned char*)(imgShow.data), imgShow.cols,                             imgShow.rows, imgShow.cols*imgShow.channels(), QImage::Format_RGB888);    ui->label->setPixmap(QPixmap::fromImage(qImg.scaled(ui->label->size(), Qt::KeepAspectRatio)));}

//Graphics View显示OpenCV图像void MainWindow::on_pushButton_2_clicked(){
   
       Mat srcImg = imread("2.jpg");    if(srcImg.empty())    {
   
           QMessageBox::information(this,"警告","图片读取失败,请检查图片路径!");        return;    }    Mat imgShow;    cvtColor(srcImg, imgShow, COLOR_BGR2RGB); // 图像格式转换    QImage qImg = QImage((unsigned char*)(imgShow.data), imgShow.cols,                             imgShow.rows, imgShow.cols*imgShow.channels(), QImage::Format_RGB888);
    QGraphicsScene *scene = new QGraphicsScene;//图像显示    ui->graphicsView->setScene(scene);    ui->graphicsView->show();    scene->addPixmap(QPixmap::fromImage(qImg));}

[4] Output result (QLabel on the left, Graphics View on the right):

picture

By default, Graphics View will automatically generate a slider when the picture is not fully displayed.

picture

Summarize

    The above demonstrates two methods of displaying images by Qt+OpenCV. The QLabel method is suitable for beginners and simple applications. Graphics View is recommended for advanced development and project use. There will be more useful articles in the future, so stay tuned!

Guess you like

Origin blog.csdn.net/stq054188/article/details/132257183