Qt+OpenCV:: Qt显示OpenCV读取的图像

背景

1、使用Qt打开文件对话窗口选择文件;

2、使用OpenCV读取图像;

3、将OpenCV读取的图像(Mat)转为Qt对象(QImage),显示到Qt窗口中;

引用头文件及命名空间

#include 
#include 
#include 
#include 

using namespace cv;

Qt打开文件对话框

QString filename=QFileDialog::getOpenFileName(this,"打开图像文件","C:\\Users\\lizhifun\\Desktop\\ModelTest\\","Image File(*.bmp;*.png;*.jpg)");

if(filename == "")
{
    QMessageBox::information(this,"提示","文件打开失败!");
    return;
}

OpenCV图像转为Qt对象

OpenCV图像为BGR格式,Qt图像为RGB格式,需要转换

Mat temp;
QImage qImg;
cv::cvtColor(img_input,temp,COLOR_BGR2RGB);
qImg = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);

完整代码

void MyWidget::on_pushButton_clicked()
{
    QString filename=QFileDialog::getOpenFileName(this,"打开图像文件","C:\\Users\\lizhifun\\Desktop\\ModelTest\\","Image File(*.bmp;*.png;*.jpg)");
    if(filename == "")
    {
        QMessageBox::information(this,"提示","文件打开失败!");
        return;
    }
    img_input = cv::imread(cv::String(filename.toLocal8Bit().toStdString()));
    if(img_input.empty())
    {
        QMessageBox::information(this,"提示","文件打开失败!");
        return;
    }
    Mat temp;
    QImage qImg;
    cv::cvtColor(img_input,temp,COLOR_BGR2RGB);
    qImg = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);

    ui->lb_img->setPixmap(QPixmap::fromImage(qImg));
    ui->lb_img->setScaledContents(true);
}

效果

Qt+OpenCV:: Qt显示OpenCV读取的图像_第1张图片     Qt+OpenCV:: Qt显示OpenCV读取的图像_第2张图片

 

程序源码:https://download.csdn.net/download/tingzhiyi/12648132

 

你可能感兴趣的:(#,OpenCV,#,Qt)