本文所介绍的技术不是原创,而是从一个叫Robert Eisele的德国人那里学习来的。他写了一个PHP扩展openCV,只封装了两个函数,叫face_detect和face_count。 openCV是一个开源的用C/C++开发的计算机图形图像库,非常强大,研究资料很齐全。本文重点是介绍如何使用php来调用其中的局部的功能。人脸侦查技术只是openCV一个应用分支。

1.安装
从源代码编译成一个动态的so文件。

1.1.安装 OpenCV (OpenCV 1.0.0)
下载地址:http://sourceforge.net/project/showfiles.php?group_id=22870&package_id=16948

#tar xvzf OpenCV-1.0.0.tar.gz
#cd opencv-1.0.0
#./configure
#make
#make install
#make check (检查是否安装全部正确)

提示: 不要指定安装路径,否则后面编译facedetect会找不到OpenCV的路径。


1.2 安装facedetect
下载地址http://www.xarg.org/download/facedetect-1.0.0.tar.gz

#tar xzvf facedetect-1.0.0.tar.gz
#cd facedetect-1.0.0
#phpize && ./configure && make && make install


编译完之后会提示facedetect.so 文件所在的位置。

最后确认在php.ini加入
extension=facedetect.so,重启apache.

2.函数使用
在phpinfo()里检查是否有facedetect这个模块。
从openCV源代码/data/haarcascades/里头取出所有xml文件放在php的执行目录下

  1. //检查有多少个脸型
  2. var_dump(face_count('party.jpeg', haarcascade_frontalface_alt.xml'));
  3. //返回脸型在图片中的位置参数,多个则返回数组
  4. $arr = face_detect('party.jpeg', haarcascade_frontalface_alt2.xml');
  5. print_r($arr);


3.应用
结合imagick可以将图片做一下应用。因为 face_detect只返回一个矩形参数,包含x,y坐标和w,h长宽参数。下面是我的一个应用demo
  1. <?php
  2. if($_FILES){
  3. $img = $_FILES['pic']['tmp_name'];
  4. $arr = face_detect($img'haarcascade_frontalface_alt2.xml');
  5. //$arr1 = face_detect($img, 'haarcascade_frontalface_alt_tree.xml');
  6. if(is_array($arr1)) $all =array_merge($arr,$arr1);
  7. else $all = $arr;
  8. $im = new Imagick($img);
  9. //$draw =new ImagickDraw();
  10. //$borderColor = new ImagickPixel('red');
  11. //$draw->setFillAlpha(0.0);
  12. //$draw->setStrokeColor  ($borderColor);
  13. //$draw->setStrokeWidth  (1);
  14. if(is_array($all)){
  15.   foreach ($all as $v){
  16.     $im_cl = $im->clone();
  17.     $im_cl->cropImage($v['w'],$v['h'],$v['x'],$v['y']);
  18.     
  19.     $im_cl->swirlImage(60);
  20.     $im->compositeImage( $im_cl, Imagick::COMPOSITE_OVER , $v['x'], $v['y'] );
  21.     
  22.     //$draw->rectangle($v['x'],$v['y'],$v['x']+$v['w'],$v['y']+$v['h']);
  23.     //$im->drawimage($draw);
  24.     
  25.     
  26.   }
  27. }
  28.   header( "Content-Type: image/png" );
  29.   echo $im;
  30. }else{
  31.   ?>
  32.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  33.   <form method="POST" enctype="multipart/form-data">
  34.   人脸识别试验:只支持jpg,png<br>
  35.   上传一张图片 <input type="file" name="pic">
  36.   <input type="submit" value="upload">
  37.   </form>
  38.   <?
  39. }
  40. ?>





参考资料:
http://www.xarg.org/2008/07/face-detection-with-php/
http://www.opencv.org.cn/index.php/首页
http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/index.html
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐