Qt & opencv 学习(二)

  

  例子:打开图片并显示。打开图片利用Qt的标准文件对话框,第一步是利用OpenCV创建窗口并显示。

  添加一个Button,转到信号槽添加代码:

 using namespace cv;
Mat image;

void Widget::on_openButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this,tr("Open Image"), ".",tr("Image Files (*.png *.jpg *.bmp)")); qDebug()<<"filenames:"<<fileName; image = cv::imread(fileName.toAscii().data()); cv::namedWindow(fileName.toAscii().data(),CV_WINDOW_AUTOSIZE)); //display use a new window cv::imshow((fileName.toAscii().data(), image); }

  代码例子来源:http://www.cnblogs.com/emouse/archive/2013/03/29/2988717.html

    1、QFileDialog::getOpenFileName()  函数原型如下:

  QString QFileDialog::getOpenFileName(QWidget * parent = 0, const QString & caption = QString(), const QString & dir = QString(), const QString & filter = QString(), QString * selectedFilter = 0, Options options = 0)

  第一个参数是父窗口指针,第二个参数是文件对话框的标题,第三个参数是文件对话框的初始路径,如果这个路径包含某个文件,那么这个文件会被处于选中状态。第4个和第5个参数的含义是Only files that match the given filter are shown. The filter selected is set to selectedFilter.第4个好理解,第5个什么意思没看懂。

 2、cv::imread()   函数原型是 Mat imread(const string& filename, int flags),就是从图片文件读取文件。

   这是一个opencv库中的c++接口,官方介绍文档在这里http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

   3、QString::toAscii() 和QByteArray::data()函数

 前者的函数原型是QByteArray QString::toAscii() const 定义是Returns an 8-bit representation of the string as a QByteArray.

   后者的函数原型是char * QByteArray::data() 定义是Returns a pointer to the data stored in the byte array. The pointer can be used to access and modify the bytes that compose the array. The data is ''-terminated, i.e. the number of bytes in the returned character string is size() + 1 for the '' terminator.

    上面的应用例子就是QString转char*。

   4、cv::cvnamedWindow()和cv::imshow是opencv里的两个常用函数。

  cvnamedWindow用于创建一个命名窗口,imshow用于在命名窗口上显示图像。

  

 补充:上面这个例子在嵌入式QT环境下还是运行不了的。出现的出错情况如下:

 

 上面这里的错误,大概是cvnamedWindow等函数是没有被实现。还不能使用。  出了问题,就换个解决方式。用下面这个函数。函数来源还是上面推荐的那个网站。

//Mat->QImage
static QImage ConvertToQImage(cv::Mat &mat)
{
    QImage img;
    int nChannel=mat.channels();
    if(nChannel==3)
    {
        cv::cvtColor(mat,mat,CV_BGR2RGB);
        img = QImage((const unsigned char*)mat.data,mat.cols,mat.rows,QImage::Format_RGB888);
    }
    else if(nChannel==4||nChannel==1)
    {
        img = QImage((const unsigned char*)mat.data,mat.cols,mat.rows,QImage::Format_ARGB32);
    }
 
    return img;
}

 

原文地址:https://www.cnblogs.com/kanite/p/5112310.html