首页 >php教程 >php手册 >基于TP3.2版人脸识别函数

基于TP3.2版人脸识别函数

WBOY
WBOY原创
2016-06-07 11:41:421318浏览

获取人的脸部特征信息,得到一组特征数组
第一步,在百度开发者中心申请人脸识别接口,具体步骤查询百度
第二步,申请成功后记下API Key和Secret Key
第三步,在框架/Library/Org/Util/目录下建立Baidu.class.php代码如下<?php<br /> <br /> /******************************************************** ******<br /> *作者:    dtnet(presdecoeur@gmail.com)<br /> *时间:      2014-6-5下午5:35:13<br /> *文件:      Bdauth.class.php<br /> ****************************************************** *******/<br /> namespace OrgUtil;<br /> <br /> class Baidu {<br />     public static $BD_OAUTH2_ENDPOINTS = array (<br />             'authorize' => 'https://openapi.baidu.com/oauth/2.0/authorize',<br>             'token' => 'https://openapi.baidu.com/oauth/2.0/token',<br>             'logout' => 'https://openapi.baidu.com/connect/2.0/logout',<br>             'face'=>'https://openapi.baidu.com/rest/2.0/media/v1/face/detect' <br>     );<br>     protected $clientId;<br>     protected $clientSecret;<br>     protected $redirectUri;<br>     public function __construct($clientId, $clientSecret) {<br>         $this->clientId = $clientId;<br>         $this->clientSecret = $clientSecret;<br>     }<br>     public function setRedirectUri($redirectUri) {<br>         if (empty ( $redirectUri )) {<br>             $redirectUri = $this->getCurrentUrl ();<br>         }<br>         $this->redirectUri = $redirectUri;<br>         return $this;<br>     }<br>     public function getRedirectUri() {<br>         return $this->redirectUri;<br>     }<br>     public function getLogoutUrl($accessToken, $next = '') {<br>         $params = array ('access_token' => $accessToken,'next' => $next ? $next : $this->getCurrentUrl () <br>         );<br>         return self::$BD_OAUTH2_ENDPOINTS ['logout'] . '?' . http_build_query ( $params, '', '&' );<br>     }<br>     public function getAuthorizeUrl($responseType = 'code', $scope = '', $state = '', $display = 'popup') {<br>         $params = array ('client_id' => $this->clientId,'response_type' => $responseType,'redirect_uri' => $this->redirectUri,'scope' => $scope,'state' => $state,'display' => $display <br>         );<br>         return self::$BD_OAUTH2_ENDPOINTS ['authorize'] . '?' . http_build_query ( $params, '', '&' );<br>     }<br>     public function getAccessTokenByAuthorizationCode($code)<br>     {<br>         $params = array(<br>                 'grant_type'    => 'authorization_code',<br>                '代码'            => $代码,<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    =>; $this->clientSecret,<br>                 'redirect_uri'    =>; $this->redirectUri,<br>         );<br>         返回 $this->makeAccessTokenRequest($params);<br>     }<br>     公共函数 getAccessTokenByClientCredentials($scope = '')<br>     {<br>         $params=数组(<br>                 'grant_type'    =>; 'client_credentials',<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    =>; $this->clientSecret,<br>                 '范围'            => $范围,<br>         );<br>         返回 $this->makeAccessTokenRequest($params);<br>     }<br>     公共函数 getAccessTokenByDeveloperCredentials($accessKey, $secretKey)<br>     {<br>         $params=数组(<br>                 'grant_type'    =>; 'developer_credentials',<br>                 'client_id'        => $accessKey,<br>                 'client_secret'    =>; $secretKey,<br>         );<br>         返回 $this->makeAccessTokenRequest($params);<br>     }<br>     公共函数 getAccessTokenByRefreshToken($refreshToken, $scope = '')<br>     {<br>         $params=数组(<br>                 'grant_type'    =>; 'refresh_token',<br>                 'refresh_token'    =>; $refreshToken,<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    =>; $this->clientSecret,<br>                 '范围'            => $范围,<br>         );<br>         返回 $this->makeAccessTokenRequest($params);<br>     }<br>     公共函数 makeAccessTokenRequest($params)<br>     {<br>        $result = $this->request(self::$BD_OAUTH2_ENDPOINTS['token'], $params, 'POST');<br>         如果($结果){<br>             $结果 = json_decode($结果, true);<br>             if (isset($result['error_description'])) {<br>                 $this->setError($result['error'], $result['error_description']);<br>                 返回 false;<br>             }<br>             返回$结果;<br>         }<br>     <br>         返回 false;<br>     }<br>     <br>     公共函数 getAccessFace($imgurl)    {<br>         <br>         $retoken=$this->getAccessTokenByClientCredentials();<br>         $imgurl=urlencode($imgurl);<br>         $params=数组(<br>                 'access_token'    =>; $retoken['access_token'],<br>                 '网址'    => $imgurl,<br>         );<br> <br>         返回 $this->makeAccessFaceRequest($params);<br>     }<br>     <br>     公共函数 makeAccessFaceRequest($params){<br>         $result = $this->request(self::$BD_OAUTH2_ENDPOINTS['face'], $params, 'POST');<br>         如果($结果){<br>             $结果 = json_decode($结果, true);<br>             if (isset($result['error_description'])) {<br>                 $this->setError($result['error'], $result['error_description']);<br>                 返回 false;<br>             }<br>             返回$结果;<br>         }        <br>         返回 false;                <br>     }<br>     <br>     <br>     公共静态函数 setError($errno, $errmsg)<br>     {<br>         self::$errno = $errno;<br>         self::$errmsg = $errmsg;<br>         self::errorLog($errmsg);<br>     }<br>     <br>     /**<br>      * 获取全局错误号。<br>      *<br>      * @return int<br>      */<br>     公共静态函数 errno()<br>     {<br>         返回自我::$errno;<br>     }<br>     <br>     /**<br>      * 获取全局错误消息。<br>      *<br>      * @return 字符串<br>      */<br>    公共静态函数 errmsg()<br>     {<br>         返回自我::$errmsg;<br>     }<br>     <br>     /**<br>      * 是否设置百度OpenAPI SDK的调试模式。<br>      *<br>      * @param bool $on true 或 false<br>      * @return void<br>      */<br>     公共静态函数 setDebugMode($on = true)<br>     {<br>         self::$isDebug = $on;<br>     }<br>     <br>     /**<br>      * 百度OpenAPI SDK的调试模式是否开启。<br>      *<br>      * @return 布尔<br>      */<br>     公共静态函数 isDebugMode()<br>     {<br>         返回 self::$isDebug;<br>     }<br>     /**<br>      * 请求 http/https 资源<br>      *<br>      * @param string $url 请求的 URL<br>      * @param array $params 请求的参数<br>      * @param string $httpMethod HTTP 方法,'GET' 或 'POST'<br>      * @param bool $multi 是否是多部分 POST 请求<br>      * @return string|false 如果成功则返回 string,如果失败则返回 false<br>      */<br>     公共静态函数请求($url, $params = array(), $httpMethod = 'GET', $multi = false)<br>     {<br>         // 使用bae(百度应用引擎)部署应用程序时,<br>         // 只需注释以下行<br>         $ch = curl_init();<br>         // 使用bae(百度应用引擎)部署应用程序时,<br>         // 并取消注释以下两行<br>         //$fetch= new BaeFetchUrl();<br>         //$ch = $fetch->getHandle();<br>     <br>         $curl_opts=数组(<br>                 CURLOPT_CONNECTTIMEOUT    => 3、<br>                 CURLOPT_TIMEOUT            => 5、<br>                 CURLOPT_USERAGENT        => 'baidu-apiclient-php-2.0',<br>                 CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,<br>                 CURLOPT_RETURNTRANSFER    => 是的,<br>                 CURLOPT_HEADER            => 假的,<br>                 CURLOPT_FOLLOWLOCATION    => 假的,<br>         );<br>    <br>         if (stripos($url, 'https://') === 0) {<br>             $curl_opts[CURLOPT_SSL_VERIFYPEER] = false;<br>         }<br>     <br>         if (strtoupper($httpMethod) === 'GET') {<br>             $query = http_build_query($params, '', '&');<br>             $delimiter = strpos($url,'?') === false? '?' : '&';<br>             $curl_opts[CURLOPT_URL] = $url。 $分隔符。 $查询;<br>             $curl_opts[CURLOPT_POST] = false;<br>         } 其他 {<br>             $headers = array();<br>             if ($multi && is_array($params) &&!empty($params)) {<br>                 $body = self::buildHttpMultipartBody($params);<br>                 $headers[] = '内容类型:多部分/表单数据; 边界='。 self::$边界;<br>             } 其他 {<br>                 $body = http_build_query($params, '', '&');<br>             }<br>             $curl_opts[CURLOPT_URL] = $url;<br>             $curl_opts[CURLOPT_POSTFIELDS] = $body;<br>             $curl_opts[CURLOPT_HTTPHEADER] = $headers;<br>         }<br>     <br>         curl_setopt_array($ch, $curl_opts);<br>         $结果=curl_exec($ch);<br>     <br>         如果($结果 === false){<br>             self::setError(curl_errno($ch), curl_error($ch));<br>             curl_close($ch);<br>             返回 false;<br>         } elseif (空($结果)) {<br>             $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);<br>             如果($http_code!= 200){<br>                 self::setError($http_code,'http 响应状态代码:''.$http_code);<br>                 curl_close($ch);<br>                 返回 false;<br>             }<br>         }<br>     <br>         curl_close($ch);<br>          <br>         返回$结果;<br>     }<br>     <br>     /**<br>      * 如果您未处于命令行模式,则打印到错误日志。<br>      *<br>      * @param 字符串日志消息<br>      */<br>    公共静态函数errorLog($msg)<br>     {<br>         // 如果我们在 CLI 环境中运行,则禁用错误日志<br>         if (php_sapi_name()!='cli') {<br>             error_log($msg);<br>         }<br>     <br>         // 如果您想在页面上看到错误,请设置调试模式<br>         if (self::$isDebug) {<br>             echo ‘error_log:’.$msg."n";<br>         }<br>     }<br>     <br>     /**<br>      * 为传递的参数生成签名。<br>      *<br>      * @param array $params 要签名的参数数组<br>      * @param string $secret 签名密钥<br>      * @param string $namespace 计算签名时排除的参数<br>      * @return string 参数签名<br>      */<br>     公共静态函数generateSign($params, $secret, $namespace = 'sign')<br>     {<br>         $str = '';<br>         ksort($params);<br>         foreach($params as $k => $v){<br>             if ($k != $namespace) {<br>                 $str .= “$k=$v”;<br>             }<br>         }<br>         $str .= $秘密;<br>         返回 md5($str);<br>     }<br>     <br>     /**<br>      * 获取当前页面的url。<br>      *<br>      * @return 字符串<br>      */<br>     公共静态函数 getCurrentUrl()<br>     {<br>         $protocol='http://';<br>         if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {<br>             $protocol=strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'])。 '://';<br>         } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {<br>             $protocol='https://';<br>         }<br>     <br>         if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {<br>             $host = $_SERVER['HTTP_X_FORWARDED_HOST'];<br>         } 其他 {<br>             $host = $_SERVER['HTTP_HOST'];<br>         }<br>     <br>         $currentUrl = $协议。 $主机。 $_SERVER['REQUEST_URI'];<br>         $parts = parse_url($currentUrl);<br>    <br>         $query = '';<br>         if (!empty($parts['query'])) {<br>             // 删除已知的 oauth 参数<br>             $params = explode('&', $parts['query']);<br>             $retained_pa​​rams = array();<br>             foreach($params 作为 $param){<br>                 if (self::shouldRetainParam($param)) {<br>                     $retained_pa​​rams[] = $param;<br>                 }<br>             }<br>                 <br>             if (!empty($retained_pa​​rams)) {<br>                 $查询 = '?' 。 内爆($retained_pa​​rams,'&');<br>             }<br>         }<br>     <br>         // 如果非默认则使用端口<br>         $port = isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) ||<br>                 ($protocol ==='https://'&& $parts['port'] !== 443))? ':'。 $parts['port'] : '';<br>     <br>         // 重建<br>         返回$协议。 $parts['host'] . $端口。 $parts['path'] . $查询;<br>     }<br>     <br>     私有静态函数shouldRetainParam($param)<br>     {<br>         foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {<br>             if (strpos($param, $drop_query_param.'=') === 0) {<br>                 返回 false;<br>             }<br>         }<br>     <br>         返回 true;<br>     }<br>     <br>     /**<br>      * 为文件上传请求构建多部分正文。<br>      * @param array $params 请求的参数<br>      * @return 字符串<br>      */<br>     私有静态函数buildHttpMultipartBody($params)<br>     {<br>         $body='';<br>         $pairs = array();<br>         self::$boundary = $boundary = md5('BAIDU-PHP-SDK-V2'. microtime(true));<br>     <br>         foreach($params as $key => $value){<br>             if ($value{0} == '@') {<br>                 $url = ltrim($value,'@');<br>                $content = file_get_contents($url);<br>                 $array = explode('?', basename($url));<br>                 $文件名=$array[0];<br>     <br>                 $body.='--'. $边界。 “rn”;<br>                 $body.='内容处置:表单数据; name="' . $key . '"; filename="' . $filename . '"'. “rn”;<br>                 $body .='内容类型:''。 self::detectMimeType($url)。 “rnrn”;<br>                 $body.=$content. “rn”;<br>             } 其他 {<br>                 $body.='--'. $边界。 “rn”;<br>                 $body.='内容处置:表单数据; name="' . $key . ""rnrn";<br>                 $body.=$value. “rn”;<br>             }<br>         }<br>     <br>         $body.='--'. $边界。 '--';<br>         返回 $body;<br>     }<br>     <br>     /**<br>      * 尝试检测文件的 MIME 类型<br>      *<br>      * 该方法将尝试使用文件信息扩展名(如果可用),<br>      * 在其他情况下不推荐使用 mime_content_type() 函数。 如果两者都不是<br>      * 有效,返回默认“application/octet-stream”MIME 类型<br>      *<br>      * @param    字符串  文件名<br>      * @return   字符串  文件 MIME 类型<br>      */<br>     私有静态函数 detectorMimeType($filename)<br>     {<br>         // 来自 PECL 的 finfo 扩展可用<br>         if (function_exists('finfo_open')) {<br>             if (!isset(self::$fileinfoDb)) {<br>                 self::$fileinfoDb = finfo_open(FILEINFO_MIME);<br>             }<br>             if (self::$fileinfoDb) {<br>                 $info = finfo_file(self::$fileinfoDb, $filename);<br>             }<br>         }<br>         //(已弃用)mime_content_type 函数可用<br>         if (空($info) && function_exists('mime_content_type')) {<br>             $info = mime_content_type($filename);<br>        }<br>         return empty($info)? 'application/octet-stream': $info;<br>     }<br> }第四步,在Common目录添加方法代码如下function face($url){<code class="prettyprint linenums lang-php">function face($url){<br>     $clientId = '这里用API Key替换';<br>     $clientSecret = '这里用Secret Key替换';<br>     $image = new OrgUtilBaidu($clientId,$clientSecret);<br>     return $image->getAccessFace($url);<br> }     $clientId = '这里用API Key替换';
    $clientSecret = '这里用Secret Key替换';
    $image = new OrgUtilBaidu($clientId,$clientSecret);
    return $image->getAccessFace($url);
}
第五步,使用函数
$url='http://xxx.xxx.com/xxx/xxx.jpg';
dump(face($url));
成功返回:
array(6) {
["face"] => array(1) {
[0] => array(3) {
["face_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["attribute"] => array(3) {
["gender"] => array(2) {
["confidence"] => string(8) "1.000000"
["value"] => string(6) "female"
}
["smiling"] => array(1) {
["confidence"] => string(8) "0.131746"
}
["face"] => array(2) {
["value"] => string(4) "true"
["confidence"] => string(4) "0.19"
}
}
["position"] => array(6) {
["center"] => array(2) {
["x"] => string(8) "0.653580"
["y"] => string(8) "0.285610"
}
["width"] => string(8) "0.624930"
["height"] => string(8) "0.468110"
["eye_left"] => array(2) {
["x"] => string(8) "0.541770"
["y"] => string(8) "0.115710"
}
["eye_right"] => array(2) {
["x"] => string(8) "0.875140"
["y"] => string(8) "0.186870"
}
["mouth"] => array(2) {
["x"] => string(8) "0.640980"
["y"] => string(8) "0.440060"
}
}
}
}
["img_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

["url"] => string(35) "http://xxx.xxx.com/xxx/xxx.jpg"

["session_id"] => string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

["img_width"] => string(3) "200" ["img_height"] => string(3) "267" AD:真正免费,域名 虚机 企业邮箱=0元
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn