Heim  >  Artikel  >  php教程  >  基于TP3.2版人脸识别函数

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

WBOY
WBOYOriginal
2016-06-07 11:41:421262Durchsuche

获取人的脸部特征信息,得到一组特征数组
第一步,在百度开发者中心申请人脸识别接口,具体步骤查询百度
第二步,申请成功后记下API Key和Secret Key
第三步,在框架/Library/Org/Util/目录下建立Baidu.class.php代码如下<?php <br /> <br> /**********************************************************<br> *Author:    dtnet(presdecoeur@gmail.com)<br> *Time:      2014-6-5下午5:35:13<br> *File:      Bdauth.class.php<br> **********************************************************/<br> namespace Org\Util;<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>                 'code'            => $code,<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    => $this->clientSecret,<br>                 'redirect_uri'    => $this->redirectUri,<br>         );<br>         return $this->makeAccessTokenRequest($params);<br>     }<br>     public function getAccessTokenByClientCredentials($scope = '')<br>     {<br>         $params = array(<br>                 'grant_type'    => 'client_credentials',<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    => $this->clientSecret,<br>                 'scope'            => $scope,<br>         );<br>         return $this->makeAccessTokenRequest($params);<br>     }<br>     public function getAccessTokenByDeveloperCredentials($accessKey, $secretKey)<br>     {<br>         $params = array(<br>                 'grant_type'    => 'developer_credentials',<br>                 'client_id'        => $accessKey,<br>                 'client_secret'    => $secretKey,<br>         );<br>         return $this->makeAccessTokenRequest($params);<br>     }<br>     public function getAccessTokenByRefreshToken($refreshToken, $scope = '')<br>     {<br>         $params = array(<br>                 'grant_type'    => 'refresh_token',<br>                 'refresh_token'    => $refreshToken,<br>                 'client_id'        => $this->clientId,<br>                 'client_secret'    => $this->clientSecret,<br>                 'scope'            => $scope,<br>         );<br>         return $this->makeAccessTokenRequest($params);<br>     }<br>     public function makeAccessTokenRequest($params)<br>     {<br>         $result = $this->request(self::$BD_OAUTH2_ENDPOINTS['token'], $params, 'POST');<br>         if ($result) {<br>             $result = json_decode($result, true);<br>             if (isset($result['error_description'])) {<br>                 $this->setError($result['error'], $result['error_description']);<br>                 return false;<br>             }<br>             return $result;<br>         }<br>     <br>         return false;<br>     }<br>     <br>     public function getAccessFace($imgurl)    {<br>         <br>         $retoken=$this->getAccessTokenByClientCredentials();<br>         $imgurl=urlencode($imgurl);<br>         $params = array(<br>                 'access_token'    => $retoken['access_token'],<br>                 'url'    => $imgurl,<br>         );<br> <br>         return $this->makeAccessFaceRequest($params);<br>     }<br>     <br>     public function makeAccessFaceRequest($params){<br>         $result = $this->request(self::$BD_OAUTH2_ENDPOINTS['face'], $params, 'POST');<br>         if ($result) {<br>             $result = json_decode($result, true);<br>             if (isset($result['error_description'])) {<br>                 $this->setError($result['error'], $result['error_description']);<br>                 return false;<br>             }<br>             return $result;<br>         }        <br>         return false;                <br>     }<br>     <br>     <br>     public static function setError($errno, $errmsg)<br>     {<br>         self::$errno = $errno;<br>         self::$errmsg = $errmsg;<br>         self::errorLog($errmsg);<br>     }<br>     <br>     /**<br>      * Get the gloable errno.<br>      *<br>      * @return int<br>      */<br>     public static function errno()<br>     {<br>         return self::$errno;<br>     }<br>     <br>     /**<br>      * Get the gloable error message.<br>      *<br>      * @return string<br>      */<br>     public static function errmsg()<br>     {<br>         return self::$errmsg;<br>     }<br>     <br>     /**<br>      * Whether to set the debug mode of the Baidu OpenAPI SDK or not.<br>      *<br>      * @param bool $on true or false<br>      * @return void<br>      */<br>     public static function setDebugMode($on = true)<br>     {<br>         self::$isDebug = $on;<br>     }<br>     <br>     /**<br>      * Whether the debug mode of the Baidu OpenAPI SDK is on or off.<br>      *<br>      * @return bool<br>      */<br>     public static function isDebugMode()<br>     {<br>         return self::$isDebug;<br>     }<br>     /**<br>      * Request for a http/https resource<br>      *<br>      * @param string $url Url to request<br>      * @param array $params Parameters for the request<br>      * @param string $httpMethod Http method, 'GET' or 'POST'<br>      * @param bool $multi Whether it's a multipart POST request<br>      * @return string|false Returns string if success, or false if failed<br>      */<br>     public static function request($url, $params = array(), $httpMethod = 'GET', $multi = false)<br>     {<br>         // when using bae(baidu app engine) to deploy the application,<br>         // just comment the following line<br>         $ch = curl_init();<br>         // when using bae(baidu app engine) to deploy the application,<br>         // and uncomment the following two lines<br>         //$fetch= new BaeFetchUrl();<br>         //$ch = $fetch->getHandle();<br>     <br>         $curl_opts = array(<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    => true,<br>                 CURLOPT_HEADER            => false,<br>                 CURLOPT_FOLLOWLOCATION    => false,<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 . $delimiter . $query;<br>             $curl_opts[CURLOPT_POST] = false;<br>         } else {<br>             $headers = array();<br>             if ($multi && is_array($params) && !empty($params)) {<br>                 $body = self::buildHttpMultipartBody($params);<br>                 $headers[] = 'Content-Type: multipart/form-data; boundary=' . self::$boundary;<br>             } else {<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>         $result = curl_exec($ch);<br>     <br>         if ($result === false) {<br>             self::setError(curl_errno($ch), curl_error($ch));<br>             curl_close($ch);<br>             return false;<br>         } elseif (empty($result)) {<br>             $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);<br>             if ($http_code != 200) {<br>                 self::setError($http_code, 'http response status code: ' . $http_code);<br>                 curl_close($ch);<br>                 return false;<br>             }<br>         }<br>     <br>         curl_close($ch);<br>          <br>         return $result;<br>     }<br>     <br>     /**<br>      * Prints to the error log if you aren't in command line mode.<br>      *<br>      * @param String log message<br>      */<br>     public static function errorLog($msg)<br>     {<br>         // disable error log if we are running in a CLI environment<br>         if (php_sapi_name() != 'cli') {<br>             error_log($msg);<br>         }<br>     <br>         // Set the debug mode if you want to see the errors on the page<br>         if (self::$isDebug) {<br>             echo 'error_log: '.$msg."\n";<br>         }<br>     }<br>     <br>     /**<br>      * Generate the signature for passed parameters.<br>      *<br>      * @param array $params Array of parameters to be signatured<br>      * @param string $secret Secret key for signature<br>      * @param string $namespace The parameter which will be excluded when calculate the signature<br>      * @return string Signature of the parameters<br>      */<br>     public static function 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 .= $secret;<br>         return md5($str);<br>     }<br>     <br>     /**<br>      * Get the url of current page.<br>      *<br>      * @return string<br>      */<br>     public static function 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>         } else {<br>             $host = $_SERVER['HTTP_HOST'];<br>         }<br>     <br>         $currentUrl = $protocol . $host . $_SERVER['REQUEST_URI'];<br>         $parts = parse_url($currentUrl);<br>     <br>         $query = '';<br>         if (!empty($parts['query'])) {<br>             // drop known oauth params<br>             $params = explode('&', $parts['query']);<br>             $retained_params = array();<br>             foreach ($params as $param) {<br>                 if (self::shouldRetainParam($param)) {<br>                     $retained_params[] = $param;<br>                 }<br>             }<br>                 <br>             if (!empty($retained_params)) {<br>                 $query = '?' . implode($retained_params, '&');<br>             }<br>         }<br>     <br>         // use port if non default<br>         $port = isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) ||<br>                 ($protocol === 'https://' && $parts['port'] !== 443)) ? ':' . $parts['port'] : '';<br>     <br>         // rebuild<br>         return $protocol . $parts['host'] . $port . $parts['path'] . $query;<br>     }<br>     <br>     private static function shouldRetainParam($param)<br>     {<br>         foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {<br>             if (strpos($param, $drop_query_param . '=') === 0) {<br>                 return false;<br>             }<br>         }<br>     <br>         return true;<br>     }<br>     <br>     /**<br>      * Build the multipart body for file uploaded request.<br>      * @param array $params Parameters for the request<br>      * @return string<br>      */<br>     private static function 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>                 $filename = $array[0];<br>     <br>                 $body .= '--' . $boundary . "\r\n";<br>                 $body .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . $filename . '"'. "\r\n";<br>                 $body .= 'Content-Type: ' . self::detectMimeType($url) . "\r\n\r\n";<br>                 $body .= $content . "\r\n";<br>             } else {<br>                 $body .= '--' . $boundary  . "\r\n";<br>                 $body .= 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n";<br>                 $body .= $value . "\r\n";<br>             }<br>         }<br>     <br>         $body .= '--' . $boundary . '--';<br>         return $body;<br>     }<br>     <br>     /**<br>      * Tries to detect MIME type of a file<br>      *<br>      * The method will try to use fileinfo extension if it is available,<br>      * deprecated mime_content_type() function in the other case. If neither<br>      * works, default 'application/octet-stream' MIME type is returned<br>      *<br>      * @param    string  filename<br>      * @return   string  file MIME type<br>      */<br>     private static function detectMimeType($filename)<br>     {<br>         // finfo extension from PECL available<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>         // (deprecated) mime_content_type function available<br>         if (empty($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){<br>     $clientId = '这里用API Key替换';<br>     $clientSecret = '这里用Secret Key替换';<br>     $image = new \Org\Util\Baidu($clientId,$clientSecret);<br>     return $image->getAccessFace($url);<br> }第五步,使用函数
$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元

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP如何将XML转成数组Nächster Artikel:Tp3.2的函数的用法!