QPixmap Qimage cv::mat转化

ui->labelImage->setPixmap(QPixmap::fromImage(qimg));  


QImage Widget::Mat2QImage(cv::Mat const& src)  
{  
     cv::Mat temp; // make the same cv::Mat  
     cvtColor(src, temp,CV_BGR2RGB); // cvtColor Makes a copt, that what i need  
     QImage dest((const uchar *) temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);  
     dest.bits(); // enforce deep copy, see documentation  
     // of QImage::QImage ( const uchar * data, int width, int height, Format format )  
     return dest;  
}  


cv::Mat Widget::QImage2Mat(QImage const& src)  
{  
     cv::Mat tmp(src.height(),src.width(),CV_8UC3,(uchar*)src.bits(),src.bytesPerLine());  
     cv::Mat result; // deep copy just in case (my lack of knowledge with open cv)  
     cvtColor(tmp, result,CV_BGR2RGB);  
     return result;  
}  

这两者内存管理机制不一样。
Memory management. cv::Mat doesn’t work like QImage in this mater. Remember thatQImage is using copy on write mechanism and shares memory for each copy.cv::Mat also shares memory but it doesn’t do copy on write (I’m also new with open cv (2 weeks) so I can’t explain yet exactly how it works but I’ve stumbled on some crushes because of that)!
Another thing is that when you are creating QImage from memory image is using this memory and doesn’t take ownership of it.
Final outcome is that on Linux and Qt5 your code is crashes because of problems with memory management. On your screen shot you can see at the top of second window that something strange is going on and you see some memory trash.
QImage的构造函数进行转换,主要是使用cv::Mat的data来构造一个QImage类型,这样做确实可以达到转换目的,但是,因此这样构造出来的QImage本身并不保存data,因此,在QImage的生存周期内,必须保证cv::Mat中的数据不会被释放。上面的这个问题也是比较容易解决的,主要是通过调用QImage::bits函数来强制QImage进行深层次复制,使得QImage自己保存一份data的副本,这样就可以保证在cv::Mat中的数据被释放的时候,QImage还能正常使用。

转载的代码 自己学习

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值