OpenCV, Qt, imread, namedWindow, imshow does not work

断了今生、忘了曾经 提交于 2019-12-01 21:00:15
karlphillip

You could also display a cv::Mat on a Qt window. I demonstrate how to do that on cvImage. The code below is adapted from cvImage::_open():

std::string filename = ...
cv::Mat mat = cv::imread(filename);

// Since OpenCV uses BGR order, we need to convert it to RGB
// NOTE: OpenCV 2.x uses CV_BGR2RGB, OpenCV 3.x uses cv::COLOR_BGR2RGB
cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB) 

// image is created according to Mat dimensions
QImage image(mat.size().width, mat.size().height, QImage::Format_RGB888);

// Copy cv::Mat to QImage
memcpy(image.scanLine(0), mat.data, static_cast<size_t>(image.width() * image.height() * mat.channels()));

// Display the QImage in a QLabel
QLabel label;
label.setPixmap(QPixmap::fromImage(image));
label.show();

First guess is that the image is in the wrong path, so first test should be to specify the full path to the image.

Also check the return value of your program (make sure the it doesn't return some crash error code - be consistent and return 0 for success and other values for fail).

And a little bit of coding that tells you where the code fails doesn't hurt, so check image.data or you can also use image.empty():

if(! image.data )
{
    std::cout << "No image to display";
    //can be any other method to display the error: qDebug, a messagebox... 
    //you can also 
    return 1;   
}
else
{
    //use the image
    //if nothing goes wrong:
    //return 0; 
}

Check Projects->Run Settings ->Run in Terminal checkbox. If it is disabled, enable it.

I faced same problem and I solved it by fixing path environment variable. In my path environment variable I added some opencv folders wrongly, then I deleted them and add only bin folder for opencv DLLs and then the problem was solved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!