OpenCV学习(二)-cv:Mat转化为QImage
OpenCV学习(2)--cv::Mat转化为QImage
版权所有,欢迎转载,转载请注明出处,谢谢
一.目的
在使用Qt和OpenCV写程序的时候,有时候需要使用OpenCV进行处理,然后使用Qt显示出来,因此,有必要考虑将如何将cv::Mat类型转换为QImage类型。
二.原理
网上主流的做法是使用QImage的构造函数进行转换,主要是使用cv::Mat的data来构造一个QImage类型,这样做确实可以达到转换目的,但是,因此这样构造出来的QImage本身并不保存data,因此,在QImage的生存周期内,必须保证cv::Mat中的数据不会被释放。上面的这个问题也是比较容易解决的,主要是通过调用QImage::bits函数来强制QImage进行深层次复制,使得QImage自己保存一份data的副本,这样就可以保证在cv::Mat中的数据被释放的时候,QImage还能正常使用。
三.代码
/** * @brief Mat2QImage Convert the cv::Mat to QImage while the cv::Mat is in BGR * color space or gray. * @param InputMat The mat used to be converted. * @return The QImage which deep copy the data of the cv::Mat. * * @author sheng * @date 2015-03-31 * @version 0.1 * * @history * <author> <date> <version> <description> * sheng 2015-03-31 0.1 build the function * */ QImage Mat2QImage(const cv::Mat& InputMat) { cv::Mat TmpMat; // convert the color space to RGB if (InputMat.channels() == 1) { cv::cvtColor(InputMat, TmpMat, CV_GRAY2RGB); } else { cv::cvtColor(InputMat, TmpMat, CV_BGR2RGB); } // construct the QImage using the data of the mat, while do not copy the data QImage Result = QImage((const uchar*)(TmpMat.data), TmpMat.cols, TmpMat.rows, QImage::Format_RGB888); // deep copy the data from mat to QImage Result.bits(); return Result; }