Qimage to Cv::Mat Convertion Strange Behaviour

cv::Mat to QImage strange behavior

I don't know. Setting an array first for me sounds like a cleaner way, see https://stackoverflow.com/a/3387400/1705967 , that could give you ideas.

Although I also use Ypnos's solution with a great success on color images. :)

Ah, and as for the second question, don't worry about the QPixmap. It makes the image data private (clones when necessary) as I have experienced so you won't overwrite it by mistake.

How to convert QImage to opencv Mat

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.

converting QImage to cv::Mat by using raw data

As constBits does indeed not work and it is not always safe to assume that the number of bytes per line will be the same (it causes a segfault for me). I found the following suggestion in StereoMatching's anwser:

cv::Mat(img.height(), img.width(), CV_8UC4, img.bits(), img.bytesPerLine()).clone()

Baradé's concern about using bits is valid, but because you clone the result the Mat will copy the data from bits, so it will not be a issue.

cv::Mat to QImage convertion not working properly

OpenCV saves the image in bgr format. This means the color values of the pixels are swapped.
If you add this line to your program the image gets displayed correctly:

  img = img.rgbSwapped();


Related Topics



Leave a reply



Submit