3

i want to convert an image from cvMat type to Qimage , with my actual code the application does not work; i have did it the other way (Qimage to Mat it work fine) please tell me what is going on wrong with my code

here is my code for Qimage to Mat :

Mat qimage2mat(const QImage& qimage) {
    cv::Mat mat = cv::Mat(qimage.height(), qimage.width(), CV_8UC4, (uchar*)qimage.bits(), qimage.bytesPerLine());
    cv::Mat mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3 );
    int from_to[] = { 0,0,  1,1,  2,2 };
    cv::mixChannels( &mat, 1, &mat2, 1, from_to, 3 );
    return mat2;
}

and here is my code for Mat to Qimage

QImage mat2qimage(const Mat& mat) {
    Mat rgb;
    cvtColor(mat, rgb, CV_BGR2RGB);
    return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888);
}

thank you by advance

ner
  • 711
  • 3
  • 13
  • 30

1 Answers1

4

as @SpamBot mentioned, the data is freed when Mat goes out of scope. try deep copying the data:

QImage mat2qimage(const Mat& mat) 
{
    Mat rgb;
    cvtColor(mat, rgb, CV_BGR2RGB);
    return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888).copy();
}
Micka
  • 19,585
  • 4
  • 56
  • 74
  • it does not work, i think that there is a problem with the format used – ner May 23 '16 at 13:27
  • this application has requested the run time to terminate it in an unusual way – ner May 23 '16 at 13:48
  • strange... for me this code seems to work... can you find out mat.type()? can you find out in which line of code it crashes? Are you able to run different OpenCV code within your program without crashing? – Micka May 23 '16 at 15:16
  • yes my application work fine without calling mat2qimage – ner May 24 '16 at 07:10