OpenCV-Qt~显示图像

  OpenCV本身提供了一些GUI方法,但使用起来仍有局限性。以C++为例,实际应用中我们大多会使用Qt或MFC来编写GUI程序。相较之下,Qt比MFC更易上手且界面样式更丰富,所以越来越多的C++视觉开发者和公司都倾向用Qt做视觉项目的GUI。

    Qt中显示OpenCV图像常用的方法有两种,一种是使用QLabel显示,另一种是QGraphicsView显示。

实现步骤

    先准备需要显示的图片,并配置好OpenCV环境(此处略过),新建Qt Widgets应用程序。

【1】添加Label控件和Graphics View控件,去除Label文字内容,添加边框。

【2】添加两个Push Button(分别命名QLabel和Graphics View),简单设计布局。

【3】转到Button对应的槽函数,添加代码:


//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】输出结果(左边QLabel,右边Graphics View):whaosoft aiot http://143ai.com

Graphics View默认在图片显示不全的情况下会自动生成滑动条。 

总  结

    上面为大家演示了Qt+OpenCV显示图像的两种方法,QLabel方法适合初学者和简单应用,进阶开发和项目使用推荐使用Graphics View。

猜你喜欢

转载自blog.csdn.net/qq_29788741/article/details/131879426