c++ - 在 cv::mat 和 Qimage 之间转换会使程序崩溃

标签 c++ qt opencv

#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/

相关文章:

c++ - OpenCV 3.0中findEssentialMat函数的使用

objective-c - Apple Mach-O 链接器和使用 OpenCV 的多个 "undefined symbols"错误

c++ - C++ 和 OpenCV 中的 SSE 均值滤波器

c++ - 不明白我是如何在结构中为变量赋值的

c++ - gcc 中的位域字节顺序

Qt:如何在 QFileDialog 上设置不区分大小写的过滤器?

python - QMediaPlayer 在 PyQt4 中不可用?

c++ - 用于多个虚拟继承和类型转换的虚拟表和虚拟指针

C++20 协程。当调用yield时,检索到空值

c++ - 如何在 QTableView/QAbstractTableModel 中使用多行文本/换行符?