Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cv::Mat to QImage conversion

Tags:

opencv

qt

I've found very similiar topic: how to convert an opencv cv::Mat to qimage , but it does not solve my problem.

I have function converting cv::Mat to QImage

QImage cvMatToQImg(cv::Mat& mat)
{
    cv::Mat rgb;
    if(mat.channels()==1)
    {
        cv::cvtColor(mat,rgb,CV_GRAY2BGR);
        cv::cvtColor(rgb,rgb,CV_BGR2BGRA);
        QImage temp = QImage((unsigned char*)(rgb.data), rgb.cols, 
                              rgb.rows,QImage::Format_ARGB32 );

        QImage returnImage = temp.copy();
        return returnImage;
}

And it's works for my but I want to make it more efficient. First: why changing 2 cvtColor functions with:

cv::cvtColor(mat,rgb,CV_GRAY2BGRA)

fails on

QImage returnImage = temp.copy() 

with segfault.

Then how to eliminate copying of QImage. When I simply return temp image, I'm getting segfault.

Any other optimalizations can be done there? It's very often used function so I want to make it as fast as possible.

like image 416
krzych Avatar asked Jun 13 '12 13:06

krzych


1 Answers

Your solution to the problem is not efficient, in particular it is less efficient then the code I posted on the other question you link to.

Your problem is that you have to convert from grayscale to color, or RGBA. As soon as you need this conversation, naturally a copy of the data is needed.

My solution does the conversion between grayscale and color, as well as between cv::Mat and QImage at the same time. That's why it is the most efficient you can get.

In your solution, you first try to convert and then want to build QImage around OpenCV data directly to spare a second copy. But, the data you point to is temporary. As soon as you leave the function, the cv::Mat free's its associated memory and that's why it is not valid anymore also within the QImage. You could manually increase the reference counter of the cv::Mat beforehand, but that opens the door for a memory leak afterwards.

In the end, you attempt a dirty solution to a problem better solved in a clean fashion.

like image 174
ypnos Avatar answered Sep 30 '22 13:09

ypnos