2014-09-10 30 views
0

我想向Qlabel显示实时相机图像。当我启动代码时,它不会给出任何错误,并且我的相机指示灯变成蓝色,这意味着工作。但是ui不启动。在我调试我的代码后,我发现它在while(true)中总是循环,但ui->lblProcessedVideo->setPixmap.....命令不显示任何UI。如何在QLabel中显示捕捉图像

您能用告诉我我的错误..

这里是我的部分代码:

void MainWindow::getImageFromVideo() 
{ 
    CvCapture* capture; 
    cv::Mat frame; 
    cv::Mat gray_frame; 

    capture = cvCaptureFromCAM(0); 

    if(capture) 
    { 
     while(true) 
     { 
      frame = cvQueryFrame(capture); 

      if(!frame.empty()) 
      { 
       cvtColor(frame, gray_frame, CV_BGR2GRAY); 

       equalizeHist(gray_frame, gray_frame); 

       ui->lblProcessedVideo->setPixmap(QPixmap::fromImage(Mat2QImage(frame))); 
      } 
     } 
    } 
} 

编辑:Mat2QImage()是转换垫的QImage

+0

是布局内的'lblProcessedVideo'标签吗?可能标签大小为'0'且内容被隐藏。也许你可以将图像保存在文件中以确保“Mat2QImage”工作正常。 – eferion 2014-09-10 08:50:59

+0

不是最好的建议,但你仍然可以尝试:在'ui-> lblProcessedVideo-> setPixmap(...'后调用'QCoreApplication :: processEvents()'。' – vahancho 2014-09-10 08:54:30

+0

@eferion yes'lblProcessVideo'正在工作我测试它当我调试代码时,我发现'Mat2QImage'也是返回值 – goGud 2014-09-10 08:57:14

回答

1

像说的Ezee你的函数需要将摄像头的捕捉图像委托给单独的线程,然后将图像发送到GUI线程。继承人示例代码:

//timer.h

class Timer : public QThread 
{ 
    Q_OBJECT 
public: 
    explicit Timer(QObject *parent = 0); 
    void run(); 
signals: 
    void updFrame(QPixmap); 
public slots: 

}; 

//timer.cpp

Timer::Timer(QObject *parent) : 
    QThread(parent) 
{ 
} 

void Timer::run() { 
    VideoCapture cap(0); // open the default camera 
    for(;;){ 
     Mat frame; 
     cap.read(frame); 
     QPixmap pix = QPixmap::fromImage(IMUtils::Mat2QImage(frame)); 
     emit updFrame(pix); 
     if(waitKey (30) >= 0){ 
      break; 
     } 
    } 
} 

//videoviewer.h

class VideoViewer : public QLabel 
{ 
    Q_OBJECT 
public: 
    explicit VideoViewer(QObject *parent = 0); 

signals: 

public slots: 
    void updateImage(QPixmap pix); 
}; 

//videoviever.cpp

VideoViewer::VideoViewer(QObject *parent) : 
    QLabel() 
{ 
    Timer* timer = new Timer(); 
    connect(timer,SIGNAL(updFrame(QPixmap)),this,SLOT(updateImage(QPixmap))); 
    timer->start(); 
} 

void VideoViewer::updateImage(QPixmap pix){ 
    this->setPixmap(pix); 
} 
+0

是的,GUI线程从来没有机会将图像绘制到标签上,因为它被收集器阻塞在代码上。 – 2014-09-10 13:33:37