I have searched on the internet but I cannot find a method of converting a QImage
(or QPixmap
) to a OpenCV Mat
. How would I do this?.
Any help is appreciated.
If the QImage will still exist, and you just need to perform a quick operation on it then you can construct a cv::Mat using the QImage memory:
cv::Mat mat(image.height(), image.width(), CV_8UC3, (cv::Scalar*)image.scanLine(0));
This assumes that the QImage is 3-channels, ie RGB888.
If the QImage is going away then you need to copy the data, see Qimage to cv::Mat convertion strange behaviour.
If QImage is Format_ARGB32_Premultiplied (the preferred format) then you will need to convert each pixel to OpenCV's BGR layout. The cv::cvtcolor() function can convert ARGB to RGB in the latest versions.
Or you can use QImage::convertToFormat() to convert to RGB before copying the data.
One year after you issued this question there've been great answers on the internet:
But the way I see it, if you're working with Qt and OpenCV at the same time then type QImage
is probably just for displaying, that case you might want to use QPixmap
since it's optimized for displaying. So this is what I do:
cv::Mat
, if you'd like to display the image, convert to QPixmap
using the non-copy method introduced in the second article.cv::Mat
.Mat2QPixmap()
to get realtime result.QPixmap
to cv::Mat
, there's no sense doing it considering the purpose of each type.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With