簡體   English   中英

使用QImage :: loadFromData將cv :: mat轉換為QImage

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

我找到了類似的主題,但沒有找到這個主題。 任何想法以下代碼有什么問題嗎? 它返回“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM