#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();
不知道发生了什么,与循环依赖有关?
最佳答案
你的函数应该是这样的:
QImage mat_to_qimage_ref(const cv::Mat3b &src) {
QImage dest(src.cols, src.rows, QImage::Format_ARGB32);
for (int y = 0; y < src.rows; ++y) {
const cv::Vec3b *srcrow = src[y];
QRgb *destrow = (QRgb*)dest.scanLine(y);
for (int x = 0; x < src.cols; ++x) {
destrow[x] = qRgba(srcrow[x][2], srcrow[x][1], srcrow[x][0], 255);
}
}
return dest;
}
关于c++ - 在 cv::mat 和 Qimage 之间转换会使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13330203/