您的位置:首页 > 编程语言 > Qt开发

Qt5下实现摄像头预览及捕获图像方法一

2016-02-29 22:27 447 查看
摘要:在Linux环境下可以通过V4L2接口及ioctl相关函数直接在底层调用摄像头设备,进行摄像头控制及图像预览和捕获,但是该方法相对比较复杂;Qt5.0版本新增了QMultimedia模块提供了更为方便的编程支持,该模块主要涵盖视频、音频、收音机以及摄像头等功能支持,提供了非常多的QML类型和C++类用以处理多媒体内容,Qt 5将Qt Multimedia模块放在了核心模块中,因此它支持所有主要平台,这些类需要在 pro 文件中添加 QT += multimedia.
平台环境:Qt5.0.2,Qt Creator(ubuntu系统),笔记本自带摄像头.
Step1:用Qt creator新建Qt Widgets Application工程
按照提示下一步即可创建模板工程,如图,并修改.pro文件添加 QT +=multimedia,QT+=multimediawidgets项

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

camera=new QCamera(this);
viewfinder=new QCameraViewfinder(this);
imageCapture=new QCameraImageCapture(camera);

ui->ImageView->addWidget(viewfinder);
ui->ImageCapture->setScaledContents(true);

camera->setViewfinder(viewfinder);
camera->start();

connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(displayImage(int,QImage)));

connect(ui->buttonCapture, SIGNAL(clicked()), this, SLOT(captureImage()));
connect(ui->buttonSave, SIGNAL(clicked()), this, SLOT(saveImage()));
connect(ui->buttonQuit, SIGNAL(clicked()), qApp, SLOT(quit()));
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::captureImage()
{
ui->statusBar->showMessage(tr("capturing..."), 1000);
imageCapture->capture();
}

void MainWindow::displayImage(int , QImage image)
{
ui->ImageCapture->setPixmap(QPixmap::fromImage(image));

ui->statusBar->showMessage(tr("capture OK!"), 5000);
}

void MainWindow::saveImage()
{
QString fileName=QFileDialog::getSaveFileName(this, tr("save file"), QDir::homePath(), tr("jpegfile(*.jpg)"));
if(fileName.isEmpty()) {
ui->statusBar->showMessage(tr("save cancel"), 5000);
return;
}
const QPixmap* pixmap=ui->ImageCapture->pixmap();
if(pixmap) {
pixmap->save(fileName);
ui->statusBar->showMessage(tr("save OK"), 5000);
}
}


View Code

Step5:编译工程效果如下



总结:QCamera类封装了很多底层操作,为了更进一步地了解Linux下摄像头的调用机制,我将在后续探讨V4L2及ioctl操作摄像头的机理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: