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

Squirrelcages picture Squirrelcages · Nov 16, 2013 · Viewed 13.1k times · Source

In the .pro file:

QT       += core

QT       -= gui

TARGET    = latihan_2
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

INCLUDEPATH += E:\OpenCV\OpenCV\opencv\build\include

LIBS += E:\OpenCV\OpenCV\opencv\build\x86\mingw\lib\libopencv_core246.dll.a
LIBS += E:\OpenCV\OpenCV\opencv\build\x86\mingw\lib\libopencv_highgui246.dll.a
LIBS += E:\OpenCV\OpenCV\opencv\build\x86\mingw\lib\libopencv_imgproc246.dll.a
LIBS += E:\OpenCV\OpenCV\opencv\build\x86\mingw\lib\libopencv_features2d246.dll.a
LIBS += E:\OpenCV\OpenCV\opencv\build\x86\mingw\lib\libopencv_calib3d246.dll.a

In main.cpp:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;

int main(){
    //read image
    Mat image = imread("img.jpg", 1);
    //create image window named "My image"
    namedWindow("My Image", CV_WINDOW_AUTOSIZE);
    //show the image on window
    imshow("My image", image);
    //wait key for 5000ms
    waitKey(5000);
    return 1;
    }

When I hit run, there is no error, but it only shows a black window named qtcreator_process_stub.exe.

Why the "My image" window doesn't come out and shows the img.jpg? I use Qt creator 2.8.1, based on Qt 5.1.1, and openCV-2.4.6.0.

Answer

karlphillip picture karlphillip · Nov 16, 2013

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();