使用Qt显示来自OpenCV的网络摄像头流

时间:2016-05-26 13:30:33

标签: c++ qt opencv opencv3.0

所以我可以通过imshow使用这个简单的代码看到我的网络摄像头流与OpenCV

int main(int, char**)
{
    VideoCapture cap(0); 
    Mat edges;
    namedWindow("webcam", 1);
    while (true)
    {
        Mat frame;
        cap >> frame; 
        imshow("webcam", frame);
        if (waitKey(30) >= 0) break;
    }
    return 0;
}

现在我想要的是在QT的Widget中的QImage中显示来自OpenCV的图像 这是从cv :: Mat到QImage的转换

QImage Mat2QImage(cv::Mat const& src)
{
    cv::Mat temp; 
    cvtColor(src, temp, CV_BGR2RGB); 
    QImage dest((const uchar *)temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
    dest.bits(); 
    // of QImage::QImage ( const uchar * data, int width, int height, Format format )
    return dest;
}

和在QT中用QImage显示图像的小代码

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QImage myImage;
    myImage.load("a.png");
    QLabel myLabel;
    myLabel.setPixmap(QPixmap::fromImage(myImage));
    myLabel.show();
    return a.exec();
}

我试图以这种方式组合它们,但没有运气

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    VideoCapture cap(0);

    QImage myImage;
    QLabel myLabel;
    while (true)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera

        myImage = Mat2QImage(frame);
        myLabel.setPixmap(QPixmap::fromImage(myImage));
    }


    myLabel.show();

    return a.exec();

2 个答案:

答案 0 :(得分:2)

您必须使用Window创建一个继承自QMainWindow的{​​{1}}。在构造函数中,将计时器连接到QTimer方法。您将openCV代码放入此超时方法,该方法将每X毫秒调用一次:

Window

然后在主屏幕中显示您的窗口:

class Window : public QMainWindow
{
    Q_OBJECT
    QTimer _timer;

    private slots:
    void on_timeout()
    {
        // put your opencv code in it
    }
    public:
    Window() :
        QMainWindow(), _timer(this)
    {
        connect(&_timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
        // populate your window with images, labels, etc. here
        _timer.start(10 /*call the timer every 10 ms*/);
    }
};

如果您使用Qt创建者,使用Qt开发更简单:想一想。

答案 1 :(得分:-1)

谢谢@Boiethios的回复 这是我把它放在mainwindow.cpp中的最终代码

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
class Window : public QMainWindow
{
    Q_OBJECT
        QTimer _timer;

    private slots:
    void on_timeout()
    {
        VideoCapture cap(0);

        Mat edges;
        namedWindow("edges", 1);
        while (true)
        {
            Mat frame;
            cap >> frame;
            myImage = Mat2QImage(frame);
            myLabel.setPixmap(QPixmap::fromImage(myImage));
            myLabel.show();
        }
    }
public:
    QImage myImage;
    QLabel myLabel;
    Window() :
        QMainWindow(), _timer(this)
    {
        connect(&_timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
        // populate your window with images, labels, etc. here
        _timer.start(10 /*call the timer every 10 ms*/);
    }
};

它编译并执行正常,但没有任何事情只是一个空白窗口

相关问题