简体   繁体   English

使用QImage :: loadFromData将cv :: mat转换为QImage

[英]Convert cv::mat to QImage using QImage::loadFromData

I've found similar topics but not this particular one. 我找到了类似的主题,但没有找到这个主题。 Any ideas what's wrong with the following code? 任何想法以下代码有什么问题吗? It returns 'loaded=false', which obviously means that image data cannot be loaded. 它返回“ loaded = false”,这显然意味着无法加载图像数据。

cv::Mat mymat;
QImage qimg;
mymat = cv::imread("C:\\testimages\\img1.png");
int len = mymat.total()*mymat.elemSize();
bool loaded = qimg.loadFromData((uchar*)mymat.data, len, "PNG");

Thank you! 谢谢!

The cv::Mat type holds a decoded image. cv::Mat类型保存已解码图像。 Thus you cannot ask QImage to decode it again using the loadFromData() method. 因此,您不能要求QImage使用loadFromData()方法再次对其进行解码。

You need to set up an image with format matching the element type, retrieved using Mat::type() , then either copy the raw data from the matrix to the image, or set up a QImage header for the data. 您需要设置一个与元素类型匹配的格式的图像,使用Mat::type()检索,然后将原始数据从矩阵复制到该图像,或者为该数据设置QImage标头。 In OpenCV terminology, a "header" means an object that doesn't hold its own data. 在OpenCV术语中,“标题”表示不持有自己数据的对象。

The code below sets up a header QImage . 下面的代码设置了头文件QImage

QMap<int, QImage::Format> fmtMap;
fmtMap.insert(CV8_UC4, QImage::Format_ARGB32);
fmtMap.insert(CV_8UC3, QImage::Format_RGB888)
// We should convert to a color image since 8-bit indexed images can't be painted on
cv::Mat mat = cv::imread("C:\\testimages\\img1.png", CV_LOAD_IMAGE_COLOR);
Q_ASSERT(fmtMap.contains(cvImage.type());
Q_ASSERT(mat.isContinuous());
QImage img(cvImage.data, cvImage.cols, cvImage.rows, fmtMap[cvImage.type()]);
// The matrix *must* outlive the image, otherwise the image will access a dangling pointer to data

It may be easier to load the image using QImage , and then create a header matrix for it. 使用QImage加载图像,然后为其创建标头矩阵,可能会更容易。

QMap<QImage::Format, int> fmtMap;
fmtMap.insert(QImage::Format_ARGB32, CV8_UC4);
fmtMap.insert(QImage::Format_RGB32, CV8_UC4);
fmtMap.insert(QImage::Format_RGB888, CV_8UC3);
QImage img;
img.load("C:\\testimages\\img1.png");
Q_ASSERT(fmtMap.contains(img.format()));
cv::Mat mat(img.height(), img.width(), fmtMap[img.format()], img.bits());
// The image *must* outlive the matrix, otherwise the matrix will access a dangling pointer to data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM