我用的是Qt5.6.0+opencv3.2,套件是MinGW,關於在Qt中如何配置的問題,可以參考這篇文章,
http://blog.csdn.net/gufeiyunshi/article/details/50967440
打開圖像做個二值化處理,以證明配置沒有問題。
在ui界面放一個label和一個pushButton,比較喜歡使用Qt做界面開發,它融合了C#和C++兩種語言的好處。
在mainwindow.h寫一個槽函數,作爲接受點,處理我們發出的指令。
private slots:
void on_pushButton_clicked();
在mainwindow.cpp輸入一下程序:
如果我們使用opencv的方法讀取圖像或者視頻到label中,需要對圖像做一個轉換,QImage類型的圖像纔可以在ui中顯示。
QImage img;
img=QImage((const unsigned char*)dstImage.data,dstImage.cols,dstImage.rows,QImage::Format_Grayscale8);
ui->label->setPixmap(QPixmap::fromImage(img));
注意新建的img是不是指針類型,顯示的是不是指針類型。然後再使用到的就是純粹opencv的知識了。
mainwindow.cpp主程序:
#include "openimage.h"
#include "ui_openimage.h"
#include <QString>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <QFileDialog>
#include <QMessageBox>
using namespace cv;
using namespace std;
QString filename;
openImage::openImage(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::openImage)
{
ui->setupUi(this);
}
openImage::~openImage()
{
delete ui;
}
void openImage::on_pushButton_clicked()
{
Mat srcImage,grayImage,dstImage;
srcImage=imread("F:/Projects_Qt/3.jpg");
cvtColor(srcImage,grayImage,CV_BGR2GRAY);
threshold(grayImage,dstImage,150,255,THRESH_BINARY);
QImage img;
img=QImage((const unsigned char*)dstImage.data,dstImage.cols,dstImage.rows,QImage::Format_Grayscale8);
ui->label->setPixmap(QPixmap::fromImage(img));
//QImage img=new QImage;
//filename=QFileDialog::getOpenFileName(this,tr("選擇圖像"),".","Images(*.png *.bmp *.jpg *tif *.GIF)::Video Files(*.avi *.mp4)");
//filename=QFileDialog::getOpenFileName(this,tr("選擇圖像"),"F:/Projects_Qt/3.jpg",tr("Images(*.png *.bmp *.jpg *tif *.GIF)"));
//if(filename.isEmpty())
//{
// return;
//}
// else
// {
// QImage* img=new QImage;
// if(!(img->load(filename)))
// {
// QMessageBox::information(this,tr("打開圖像失敗"),tr("打開圖像失敗"));
// delete img;
// return;
// }
// ui->label->setPixmap(QPixmap::fromImage(*img));
// }
}
上面註釋的是尋找文件的方法顯示圖像,不利用opencv處理圖像,不建議使用,但是沒有配置opencv的可以用注掉的程序顯示圖像。
最後的處理結果: