QPixmap Qimage cv::mat conversion

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.
The constructor of QImage performs conversion, mainly using the data of cv::Mat to construct a QImage type. This can indeed achieve the purpose of conversion. However, the QImage itself constructed in this way does not save data. Therefore, in the survival of QImage During the period, it must be ensured that the data in cv::Mat will not be released. The above problem is also relatively easy to solve, mainly by calling the QImage::bits function to force QImage to perform a deep copy, so that QImage itself saves a copy of the data, so that the data in cv::Mat can be guaranteed to be When released, QImage can still be used normally.

Reprinted code to learn by yourself

Guess you like

Origin blog.csdn.net/u012842273/article/details/54410128