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

Convert cv::mat to QImage using QImage::loadFromData

本文关键字:QImage 转换 mat loadFromData 使用 cv      更新时间:2023-10-16

我发现了类似的主题,但没有这个特定的主题。任何想法以下代码有什么问题?它返回'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");

谢谢!

cv::Mat 类型保存解码的图像。因此,您不能要求QImage使用 loadFromData() 方法再次解码它。

您需要设置格式与元素类型匹配的图像,使用 Mat::type() 检索,然后将原始数据从矩阵复制到图像,或为数据设置QImage标头。在OpenCV术语中,"标头"是指不保存自己的数据的对象。

下面的代码设置了一个标头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

使用 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