天天看点

电脑摄像头拍照

一个简陋的摄像头拍照工具,能将拍到的照片保存为.png文件。

使用Qt+openCV实现。

#include "qtusecamera.h"
#include<opencv/cv.h>
#include<opencv/highgui.h>
#include<windows.h>

QtUseCamera::QtUseCamera(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags)
{
	preReadLabel = new QLabel;
	photoLabel =new QLabel;
    openBut = new QPushButton("打开");
    takeBut = new QPushButton("拍照");
    closeBut=new QPushButton("关闭");
    saveBut=new QPushButton("保存");
	labelLayout=new QHBoxLayout;
	butLayout=new QHBoxLayout;
	mainLayout=new QVBoxLayout;
	labelLayout->addWidget(preReadLabel);
	labelLayout->addWidget(photoLabel);
	butLayout->addWidget(openBut);
	butLayout->addWidget(takeBut);
    butLayout->addStretch();
    butLayout->addWidget(saveBut);
    butLayout->addWidget(closeBut);
    butLayout->setContentsMargins(10,5,10,5);
	mainLayout->addLayout(labelLayout);
	mainLayout->addLayout(butLayout);
	mainLayout->setSpacing(1);
	mainLayout->setContentsMargins(0,0,0,0);
	setLayout(mainLayout);

	timer=new QTimer;
	connect(openBut,SIGNAL(clicked()),this,SLOT(openCamera()));
	connect(takeBut,SIGNAL(clicked()),this,SLOT(takingPictures()));
	connect(closeBut,SIGNAL(clicked()),this,SLOT(closeCamera()));
	connect(timer,SIGNAL(timeout()),this,SLOT(readFrame()));
    connect(saveBut,SIGNAL(clicked()),this,SLOT(savePic()));

	cam=NULL;
    resize(200,200);
    setWindowTitle("摄像头拍照");
}

QtUseCamera::~QtUseCamera()
{
	cvReleaseCapture(&cam);
}

void QtUseCamera::openCamera(){
	cam = cvCreateCameraCapture(0);
	Sleep(1000);
	timer->start(30);
}
void QtUseCamera::readFrame(){
	if(!cam) return ;
	frame = cvQueryFrame(cam);
	QImage image = QImage((const uchar*)frame->imageData,
		frame->width,
		frame->height, 
		QImage::Format_RGB888).rgbSwapped();
	preReadLabel->setPixmap(QPixmap::fromImage(image));
}
void QtUseCamera::closeCamera(){
	timer->stop();
	cvReleaseCapture(&cam);
    preReadLabel->setPixmap(QPixmap());
    photoLabel->setPixmap(QPixmap());
    takePic=QImage();
    resize(200,200);
}
void QtUseCamera::takingPictures(){
	if(!cam) return ;
	frame = cvQueryFrame(cam);
    takePic = QImage((const uchar*)frame->imageData,
		frame->width,
		frame->height, 
		QImage::Format_RGB888).rgbSwapped();
    photoLabel->setPixmap(QPixmap::fromImage(takePic));

}

void QtUseCamera::savePic(){
    if(takePic.isNull()) return ;
    QString fileName=QFileDialog::getSaveFileName(this,"保存照片",QString(),"png file(*.png)");
    if(fileName.isEmpty()) return ;
    takePic.save(fileName,"png",100);

}
           

http://download.csdn.net/detail/thatmaybefun/7025779