vs2013+opencv2.4.9+qt5.6实现拍照并保存功能

软件的安装以及配置按网上的教程就可以,这里用到opencv打开摄像头并进行拍照,然后在ui界面上显示,这里需要将图片的数据进行转换—Mat与Pixmap的相互转换,接下来就以具体的代码进行说明吧。

一、ui界面的设计


二、代码的实现

编辑QtGui_Capture.h文件

#pragma once

#include <QtWidgets/QWidget>
#include "ui_QtGui_Capture.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <QImage>
#include <QTimer>

using namespace cv;
using namespace std;

class QtGui_Capture : public QWidget
{
	Q_OBJECT

public:
	QtGui_Capture(QWidget *parent = Q_NULLPTR);

private:
	Ui::QtGui_CaptureClass ui;
private slots:
        void openCameraSlot(); 
	void readFrame();
	void closeCameraSlot();
	void capturePictureSlot();
private:
	QTimer *timer;
	QImage *img;
	VideoCapture cap;  //视频获取结构,用来作为视频获取函数的一个参数
	Mat frame;  //Mat类型,每一帧存放位置
	QImage Mat2QImage(Mat cvImg);
};

编辑QtGui_Capture.cpp文件:

信号槽连接:

QtGui_Capture::QtGui_Capture(QWidget *parent)
	: QWidget(parent)
{
	timer = new QTimer(this);
	img = new QImage();
	ui.setupUi(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(readFrame()));
	connect(ui.openCameraButton, SIGNAL(clicked()), this, SLOT(openCameraSlot()));
	connect(ui.capturePicButton, SIGNAL(clicked()), this, SLOT(capturePictureSlot()));
	connect(ui.closeCameraButton, SIGNAL(clicked()), this, SLOT(closeCameraSlot()));
}

槽函数的定义:

//打开摄像头
void QtGui_Capture::openCameraSlot()
{
	cap.open(0);
	if (!cap.isOpened())
	{
	   printf("frame is empty\n");	
	}
	timer->start(40);
}
void QtGui_Capture::readFrame()
{
	cap >> frame;//读取当前帧
	//将抓取到的帧,转换为QImage格式。QImage::Format_RGB888不同的摄像头用不同的格式
	QImage img = Mat2QImage(frame);
	ui.label->setScaledContents(true);
	ui.label->setPixmap(QPixmap::fromImage(img));
}
void QtGui_Capture::capturePictureSlot()
{
	cap >> frame;
	QImage img= Mat2QImage(frame);
	ui.label_2->setScaledContents(true);
	ui.label_2->setPixmap(QPixmap::fromImage(img));
}

//Mat与Pixmap格式转换
QImage QtGui_Capture::Mat2QImage(Mat cvImg)
{
	Mat cvRgbImg;   
	cvtColor(cvImg, cvRgbImg, CV_BGR2RGB);  
	QImage dstImage((const uchar *)cvRgbImg.data, cvRgbImg.cols, cvRgbImg.rows, cvRgbImg.step, QImage::Format_RGB888);
	dstImage.bits();    	                
	return dstImage;
}
//关闭摄像头,并将当前画面清除
void QtGui_Capture::closeCameraSlot()
{
	timer->stop();
	ui.label->clear();
	cap.release();
}

最后显示效果图如下:

最后图片也自动保存在了当前文件夹下面


文中如果有什么错误之处希望各位读者可以指出,在此先谢过了


猜你喜欢

转载自blog.csdn.net/zkz10086/article/details/80566109