日期:2014-05-16  浏览次数:21182 次

如何使用opencv 连接多个摄像头
系统是UBUNTU-11.04
opencv版本是2.4.6.1
摄像头是微星z301p
两个USB摄像头用hub连接
将两个摄像头视频同时显示到Qt界面中
-------------------------
代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

#include <QImage>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    cam=NULL;
    cam_2=NULL;
    timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(readCamera()));
    connect(ui->open,SIGNAL(clicked()),this,SLOT(openCamera()));
    connect(ui->close,SIGNAL(clicked()),this,SLOT(closeCamera()));

}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::openCamera()
{
    cam=cvCaptureFromCAM(200);//CV_CAP_V4L2
    if(!cam)
    {
        qDebug("create camera1 capture error!");
    }
    cam_2=cvCaptureFromCAM(201);//CV_CAP_V4L2+1
    if(!cam_2)
    {
        qDebug("create camera2 capture error!");
    }
    timer->start(33);
}
void MainWindow::readCamera()
{

    frame_2=cvQueryFrame(cam_2);
    if(!frame_2)
    {
        qDebug("get frame2 error!");
        return;
    }
    QImage image_2=QImage((const uchar*)frame_2->imageData, frame_2->width, frame_2->height, QImage::Format_RGB888).rgbSwapped();//rgbSwapped()用于转换QImage对象从RGB->BGR
    ui->label_2->setPixmap(QPixmap::fromImage(image_2));

    frame=cvQueryFrame(cam);
    if(!frame)
    {
        qDebug("get frame1 error!");
        return;
    }
    QImage image=QImage((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888).rgbSwapped();//rgbSwapped()用于转换QImage对象从RGB->BGR
    ui->label->setPixmap(QPixmap::fromImage(image));
}

void MainWindow::closeCamera()
{
    timer->stop();
    cvReleaseCapture(&cam);
    cvReleaseCapture(&cam_2);
}

则开始后两个摄像图均无画面显示,并输出错误:
/root/Qtworkspace/TestOpenCv-build-desktop/TestOpenCv 启动中...
HIGHGUI ERROR: V4L/V4L2: VIDIOC_CROPCAP
HIGHGUI ERROR: V4L/V4L2: VIDIOC_CROPCAP
select timeout
select timeout
OpenCV Error: Assertion failed (buf.data && buf.isContinuous()) in imdecode_, file /root/package/opencv-2.4.6.1/modules/highgui/src/loadsave.cpp, line 307
terminate called after throwing an instance of 'cv::Exception'
  what():