2014-09-10 78 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