之前记录了直接使用opencv的imread函数读取特定位置的图片,这次实现一个电脑上任意位置的文件读取的功能。在这里需要用到QFileDialog这个静态函数,返回用户选择的文件名,如果用户选择取消或者关闭窗口,则返回一个空串。函数形式如下:
QString QFileDialog::getOpenFileName( QWidget * parent = 0, const QString & caption = QString(), const QString & dir = QString(), const QString & filter = QString(), QString * selectedFilter = 0, Options options = 0 );
调用该函数会新建一个模态的文件对话框,在CPP文件顶部加上这一功能的函数
```python
#include
首先在ui界面新建一个label用于放置图片,一个button放置按钮,如图所示
在按钮那里转到槽,写入以下代码,实现图片文件读取与图片显示到
void MainWindow::on_pushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Open Image"),".",tr("Image File(*.png *.jpg *.jpeg *.bmp)"));
Mat image = cv::imread(fileName.toLatin1().data());
cv::cvtColor(image,image,CV_BGR2RGB);
QImage img = QImage((const unsigned char*)(image.data),image.cols,image.rows,QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(img));
ui->label->setScaledContents(true);
ui->label->show();
}
但是刚才写的代码具有很大的局限性,如果直接点击了取消或者关闭窗口,会导致程序报错,因为写的代码是默认读取了图片的,这时为了点击了取消或者关闭窗口也能顺利运行,加一个条件判断。
if(fileName.length()==0)
{
QMessageBox::information(NULL,tr("fileName"),tr("you don't select anyfile"));
}
如果读取的文件名的长度为0,即没有读取到文件,则显示此窗口
否则
else
{
QMessageBox::information(NULL, tr( "Path"), tr( "You selected ") + fileName);
Mat image = cv::imread(fileName.toLatin1().data());
cv::cvtColor(image,image,CV_BGR2RGB);
QImage img = QImage((const unsigned char*)(image.data),image.cols,image.rows,QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(img));
ui->label->setScaledContents(true);
ui->label->show();
}