search

php使用face++实现一个简单的人脸识别系统

流程

流程可以分为两部分,一部分是训练,一部分是测试。

关于如何使用face++提供的API可以看http://blog.csdn.net/jianjian1992/article/details/46640483

代码可在http://download.csdn.net/detail/jianjian1992/8866839免费下载。


起始界面

界面

如下所示,将使用说明进行了介绍,因为是初次使用,很多不太会,所以界面弄得比较简单,以能使用为第一目标。


实现细节

index.html是欢迎界面,记录一下几个小问题

中文的使用

在head部分加上字符集使用utf-8就好啦!

 <meta http-equiv="Content-Type" content="text/html; charset = utf-8">

文字居中与背景设置

在html最前面加了个style,设置body的显示效果。

文字显示设置为居中,使用height,width加上margin-top,margin-left便可以设置body部分在页面中显示的地方啦。

背景则设置了图片url,以及居中显示。

<style>body{	text-align:left; 	height:500px;	width:600px;	top:50%;	margin-top:130px;	margin-left:550px;	background-image:url(./imgs/back.jpg);	background-position:center;	background-repeat:repeat-y;}</style>

按钮的页面跳转

onClick里面用location记录将要跳转的界面。

<input type="button" value="点击进入测试" onclick="location='test.php' ">

训练部分

包括两部分:

  • startTrain.php用于输入训练目录,
  • train.php用于将训练数据传到服务器,并将训练成功标记输出

startTrain.php

这一部分做得蛮挫的,查了下php选择文件夹,没有找到该怎么做,所以就用了个来输入目录。真是弱爆了啊大笑

用了一个表单form来记录输入目录,提交表单之后则跳到train.php中进行真正的训练啦。







train.php

这一部分实现了两个功能:

  • 根据输入目录查找所有训练图片,并记录所有图片路径
  • 将所有训练图片一一检测人脸,并将人脸加入到训练模型中


查找目录

php中查找目录中所有文件倒是挺方便的啊,listDir函数在dir.php中。

这个函数根据$dir目录名,将得到的所有文件名存入$names,所有文件路径名则存入$img_urls中。

注意的一点是,如果是中文文件名,则要加上

$file = iconv("gb2312","UTF-8",$file);
这一句才会得到结果的,要不就是空哦

php中字符串的查找可以使用strstr函数,

比如下面的$file_name = strstr($file,'.',true)便是查找$file中‘.’的前面部分,如果是strstr($file,'.',false)则是'.'的后面部分。

动态数组的添加使用array_push就ok啦!

哦,不要忘记了关闭资源啊!有opendir($dir)那么就要有对应的closedir($dir)。

function listDir($dir, &$names, &$img_urls){	if(is_dir($dir))   	{     	if ($dh = opendir($dir)) 		{        	while (($file = readdir($dh)) !== false)			{				     			if((is_dir($dir."/".$file)) && $file!="." && $file!="..")				{     				//echo "文件名:",$file,"

"; listDir($dir."/".$file."/"); } else { $file = iconv("gb2312","UTF-8",$file); if($file!="." && $file!="..") { //var_dump($file); $file_name = strstr($file, '.', true); //echo $file_name."
"; array_push($names, $file_name); array_push($img_urls, $dir."/".$file); } } } closedir($dh); } }}


在train.php中使用如下代码便得到了训练用的所有图片的url啦。

$img_url = array();$person_name = array();$trainDir = $_GET["trainDir"];listDir($trainDir, $person_name, $img_url);echo "从目录中我们得到了 ".sizeof($img_url)." 张图片".<br>;
接着我们创建一个训练组oldpeople_qiaoxi。
$response = $facepp->execute('/group/delete', array('group_name' => 'oldpeople_qiaoxi'));$response = $facepp->execute('/group/create', array('group_name' => 'oldpeople_qiaoxi'));
接着做循环,对每张图片检测人脸

$params['img']          = $img;$params['attribute']    = 'gender,age,race,smiling,glass,pose';$response               = $facepp->execute('/detection/detect',$params);
从返回值$response得到face_id之后,创建一个person并将检测到的人脸加入这个类别person中。

$response = $facepp->execute('/person/delete', array('person_name' => $person_name[$i],'group_name' => 'oldpeople_qiaoxi'));$response = $facepp->execute('/person/create', array('person_name' => $person_name[$i],'group_name' => 'oldpeople_qiaoxi'));$response = $facepp->execute('/person/add_face', array('person_name' => $person_name[$i], 'face_id' => $face_id, 'group_name' => 'oldpeople_qiaoxi'));
将所有图片都处理好之后,便可以训练模型了。

$response = $facepp->execute('/train/identify', array('group_name' => 'oldpeople_qiaoxi'));
训练成功的话,结果如下:



测试部分

这个部分包括2个部分:

  • test.php负责选择测试图片
  • recognition.php负责将测试图片传到服务器并给出结果

test.php部分

显示如下:

选择文件部分用的是来做的,之后表单提交到recognition.php就好了。




recognition.php部分

首先得到图片的url。

$img_url = $_GET["testImgPath"];
之后执行identify得到身份结果。

$response = $facepp->execute('/recognition/identify', array('group_name' => 'oldpeople_qiaoxi', 'img' => $img_url));
这里采用了一个数组来进行中文名与英文名的对应,因为face++不支持中文名的图片,所以传给它的图片都是英文命名的,但是显示需要中文名,所以在这里进行映射。

$person_name = array("ami" => "艾米", "dongjian" => "张东健", "xiaowang" => "小王");







$img_url = array();$person_name = array();$trainDir = $_GET["trainDir"];listDir($trainDir, $person_name, $img_url);echo "从目录中我们得到了 ".sizeof($img_url)." 张图片".<br>;


版权声明:本文为博主原创文章,未经博主允许不得转载。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.