Qt调用摄像机一般有两种方法,一种是使用QCamera,另一种是使用openCV。
不同的Qt版本QCamera差别很大,相互之间不兼容,不过不同版本的openCV函数差别不大,。这里使用openCV调用摄像机进行录像,并显示在QGraphicsView上。
cv::VideoCapture cap;
QTimer timer;//计时器,持续捕获相机上的图像
QGraphicsView *graphicsview=new QGraphicsView(this);
graphicsview->setGeometry(0,0,600,600);//位置大小自己调
QgraphicsScene *scene=new QGraphicsScene(this);
graphicsview.setScene(scene);
cap = cv::VideoCapture(0);//有相机连接的话,使用默认的第一个相机。
if (!cap.isOpened()) {
QMessageBox::information(nullptr, "打开相机失败", "未识别到可用的相机");
}
else{
connect(&timer, &QTimer::timeout, this, [this]() {
cv::Mat frame;
cap >> frame;//捕获图像,传递给frame
if (frame.empty()) {
qDebug() << "无法获取摄像头图像";
return;
}
QImage img(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
QPixmap pixmap = QPixmap::fromImage(img.rgbSwapped());
scene->clear();//在加载图像前,需要把上一个图像清除
scene->addPixmap(pixmap);
graphicsview->fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);
}
}