#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <QtGui>
//make QImage point to the contents of cv::Mat
inline QImage const mat_to_qimage_ref(cv::Mat &mat)
{
return QImage((unsigned char*)(mat.data), mat.cols, mat.rows, mat.step1(), QImage::Format_RGB32);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage img("lena2.jpg");
cv::Mat mat(img.height(), img.width(), CV_8UC4, img.bits(), img.bytesPerLine());
QImage img = mat_to_qimage_ref(mat); //#1
//QImage img2((unsigned char*)(mat.data), mat.cols, mat.rows, mat.step, QImage::Format_RGB32); #2
QLabel label;
label.setPixmap(QPixmap::fromImage(img)); //crash at here
label.show();
return a.exec();
}
(#2) 没问题,但#1 会发生未定义的行为?(我的情况是崩溃)
此外,如果您使用它作为下面的代码,就可以了
cv::Mat img = cv::imread("lena2.jpg");
QLabel label;
label.setPixmap(QPixmap::fromImage(mat_to_qimage_ref(img)));
label.show();
不知道发生了什么,与循环依赖有关?