gpt4 book ai didi

c++ - 使用 QImage::loadFromData 将 cv::mat 转换为 QImage

转载 作者:行者123 更新时间:2023-11-28 07:23:10 30 4
gpt4 key购买 nike

我找到了类似的主题,但不是这个特定的主题。知道以下代码有什么问题吗?它返回'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 术语中,“ header ”是指不包含自己数据的对象。

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

关于c++ - 使用 QImage::loadFromData 将 cv::mat 转换为 QImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145424/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com