#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPixmap logo(QDir::currentPath() + "/opencv.jpg");
ui->label_video->setPixmap(logo);
connect(this, SIGNAL(getQimage(cv::Mat&)), this, SLOT(showimage(cv::Mat&)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Sleep(int msec)
{
QTime dieTime = QTime::currentTime().addMSecs(msec);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
void MainWindow::deldir(QString &path)
{
if (path.isEmpty())
return ;
QDir dir(path);
if(!dir.exists())
return ;
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
QFileInfoList fileList = dir.entryInfoList();
foreach (QFileInfo fi, fileList)
{
if (fi.isFile())
fi.dir().remove(fi.fileName());
//else
// ; //DeleteDirectory(fi.absoluteFilePath());
}
return ;
}
void MainWindow::on_pushButton_photo_sample_clicked()
{
PhotoIn = new Dialogin(this);
PhotoIn->setMaximumSize(QSize(670,610));
PhotoIn->setMinimumSize(QSize(670,610));
PhotoIn->show();
}
void MainWindow::on_pushButton_train_clicked()
{
QMessageBox *startbox = new QMessageBox(QMessageBox::Warning ,"信息","开始训练请稍后!!!",QMessageBox::NoButton,this);
startbox->show();
Sleep(1000);
QFile csv(QDir::currentPath() + "/csv.txt");
if(!csv.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << csv.errorString() <<endl;
startbox->close();
QMessageBox::warning(this,tr("错误"),tr("csv文件未找到!!!"),QMessageBox::Ok);
return;
}
std::vector<cv::Mat>images;
std::vector<int>labels;
while(!csv.atEnd())
{
QString p = csv.readLine(128);
QStringList qlist = p.split(";");
if(qlist.size() == 2)
{
QString a =qlist[0];
QByteArray b = a.toLatin1();
char *path = b.data();
// char *path = (qlist[0].toLatin1()).data();
int tag = qlist[1].mid(0, 1).toInt();
std::string filepath =cv::format(path);
images.push_back(cv::imread(path, 0));
labels.push_back(tag);
qDebug()<< qlist.size() <<endl;
}
}
if(images.size() < 1)
{
QMessageBox::warning(this,tr("错误"),tr("加载图片失败!!!"),QMessageBox::Ok);
return;
}
cv::Ptr<cv::FaceRecognizer> model = cv::createEigenFaceRecognizer();
model->train(images, labels);
model->save("facemodel.xml");
startbox->close();
QMessageBox::warning(this,tr("信息"),tr("恭喜模型训练完成!!!"),QMessageBox::Ok);
}
void MainWindow::on_pushButton_face_reco_clicked()
{
CvCapture* capture = cvCaptureFromCAM(0); //打开默认摄像头
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 640);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 480);
if (capture == NULL)
{
QMessageBox::warning(this,tr("错误"),tr("摄像头打开失败"),QMessageBox::Ok);
return;
}
cv::Mat frame;
cv::Mat gray;
cv::CascadeClassifier faceClassifier;
//训练好的文件名称,放置在可执行文件同目录下
bool flag =faceClassifier.load("haarcascade_frontalface_alt.xml");
if(flag == false)
{
QMessageBox::warning(this,tr("错误"),tr("不能加载haarcascade_frontalface_alt.xml文件!!"),QMessageBox::Ok);
return;
}
QFile facemodel(QDir::currentPath() + "/facemodel.xml");
if(!facemodel.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << facemodel.errorString() <<endl;
cvReleaseCapture(&capture);
QMessageBox::warning(this,tr("错误"),tr("facemodel.xml文件未找到!!!"),QMessageBox::Ok);
return;
}
cv::Ptr<cv::FaceRecognizer> model = cv::createEigenFaceRecognizer();
model->load("facemodel.xml");
stopflag = true;
while(stopflag == true)
{
Sleep(100);
frame = cvQueryFrame( capture );
std::vector<cv::Rect> faces;
//RGB转BGR格式
cv::cvtColor(frame, gray, CV_BGR2GRAY);
//变换后的图像进行直方图均值化处理
cv::equalizeHist(gray, gray);
//通过人脸分类器识别有多少人脸
faceClassifier.detectMultiScale(gray, faces, 1.1, 2, cv::CASCADE_FIND_BIGGEST_OBJECT|cv::CASCADE_DO_ROUGH_SEARCH, cv::Size(50, 50));
//qDebug() << "faces.size =" << faces.size() << endl;
cv::Mat face;
for (size_t i = 0; i < faces.size(); i++)
{
//imshow("face", face[i]);
if (faces[i].height > 0 && faces[i].width > 0)
{
face = gray(faces[i]);
cv::rectangle(frame, faces[i], cv::Scalar(0, 0, 255), 1, 8, 0);
emit getQimage(frame);
}
}
if(faces.size() == 0)
{
ui->lineEdit_confidence->clear();
ui->lineEdit_user->clear();
emit getQimage(frame);
}
cv::Mat face_test;
if((face.rows > 112) || (face.cols > 92))
{
cv::resize(face, face_test, cv::Size(92,112));
}
//int predictPCA = 0;
double confidence=0.0;
if (!face_test.empty())
{
//测试图像应该是灰度图
int predictedLabel=-1;
//predictPCA = model->predict(face_test);
model->predict(face_test,predictedLabel,confidence);
ui->lineEdit_confidence->setText(QString::number(confidence));
// qDebug() << "predictPCA =" << predictPCA << endl;
// qDebug()<<"predictedLabel:"<<predictedLabel;
// qDebug()<<"confidence:"<<confidence;
QFile user(QDir::currentPath() + "/usr.txt");
if(!user.open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << user.errorString() <<endl;
}
qint64 usrlinenum =0;
//usrlinenum=1;
QString line;
QTextStream in(&user);
while((!in.atEnd()) && (usrlinenum < predictedLabel) )
{
line = in.readLine();
usrlinenum++;
}
QStringList list = line.split(";");
ui->lineEdit_user->setText(list[1]);
}
}
cvReleaseCapture(&capture);
QPixmap logo(QDir::currentPath() + "/opencv.jpg");
ui->label_video->setPixmap(logo);
}
void MainWindow::showimage(cv::Mat &image)
{
cv::Mat src = image ;
cvtColor( src, src, CV_BGR2RGB );
QImage img=QImage((const unsigned char*)(src.data), src.cols, src.rows, QImage::Format_RGB888);
QPixmap pix = QPixmap::fromImage(img);
ui->label_video->setPixmap(pix);
}
void MainWindow::on_pushButton_face_reco_stop_clicked()
{
stopflag = false;
}
void MainWindow::on_pushButton_clear_data_clicked()
{
QString path = QDir::currentPath();
QFile facemodel(path + "/facemodel.xml");
if(facemodel.exists())
{
facemodel.remove();
}
QFile csv(path + "/csv.txt");
if(csv.exists())
{
csv.remove();
}
// QString dirpath = path + "/TEMP";
// deldir(dirpath);
// dirpath = path + "/"
}