cv :: Mat到QImage转换 [英] cv::Mat to QImage conversion

查看:283
本文介绍了cv :: Mat到QImage转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个非常相似的主题:如何转换opencv cv :: Mat转换为qimage ,但这并不能解决我的问题.

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

我具有将cv :: Mat转换为QImage的功能

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;
}

它适用于我,但我想使其更高效. 第一:为什么要使用以下方式更改2个cvtColor函数:

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)

失败

QImage returnImage = temp.copy() 

带有段错误.

然后如何消除QImage的复制.当我只返回临时图像时,就会遇到段错误.

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.

推荐答案

您对问题的解决方案效率不高,特别是效率不如我在您链接到的另一个问题上发布的代码.

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.

您的问题是您必须从灰度转换为彩色或RGBA.一旦您需要此对话,自然就需要数据的副本.

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.

我的解决方案同时在灰度和颜色之间以及cv :: Mat和QImage之间进行转换.这就是为什么它是您可以获得的最有效的.

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.

在您的解决方案中,您首先尝试进行转换,然后想要直接围绕OpenCV数据构建QImage,以保留第二个副本.但是,您指向的数据是临时的.离开函数后,cv :: Mat会释放其关联的内存,这就是为什么它在QImage中也不再有效的原因.您可以事先手动增加cv :: Mat的引用计数器,但这随后会打开内存泄漏的大门.

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.

这篇关于cv :: Mat到QImage转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆