最近,公司准备用到图像识别技术,所以特地看了百度提供的接口文档
下面是代码:
1、现在app.php中配置在百度控制台创建的appid和secret,方便管理
'baidu_appId' => '',
'baidu_secret' => '',
2、通过百度提供的demo代码,copy对应的curl请求方法到公共文件
//路径:application\common.php
function curlPost($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
// 初始化curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_HEADER, 0);
// 要求结果为字符串且输出到屏幕上
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// post提交方式
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
// 运行curl
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
3、在控制器中调用,先获取access_token,并存储到缓存中,可设置有效期不超过30天,因为百度提供的access_token有效期就是30天内;然后再调用对应的识别api就可以了
//获取access_token
public function getToken()
{
$appid = config('baidu_appId');
$secret = config('baidu_secret');
$token = Cache::store('redis')->get('baidu_token');
if($token){
return $token;
die();
}
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = $appid;
$post_data['client_secret'] = $secret;
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$res = curlPost($url, $post_data);
$res = json_decode($res, true);
// dump($res);
if($res['access_token']){
Cache::store('redis')->set('baidu_token', $res['access_token']);
return $res['access_token'];
}else{
return false;
}
die();
}
// 图像识别,以植物识别为例
public function imagePlantCheck()
{
//可以是url,或者是已经上传到服务器的图片路径
$img = input('post.img');
// 类型:1为网络图片地址 2为本地资源
$check_type = input('post.check_type');
$token = $this->getToken();
if(!$token){
return json_encode(array('code'=>100,'msg'=>'调用失败'));
die();
}
$url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=' . $token;
if($check_type == 1){
$bodys = array(
'url' => $img,
'baike_num' => 5
);
$res = curlPost($url, $bodys);
}
if($check_type == 2){
$imgPath = $img;
$img = file_get_contents($img);
$img = base64_encode($img);
$bodys = array(
'image' => $img,
'baike_num' => 5
);
$res = curlPost($url, $bodys);
}
$res = json_decode($res, true);
if(isset($res['error_code'])){
$status = 0;
$msg = $res['error_msg'];
}else{
$status = 1;
$msg = 'success';
}
if(isset($res['error_code'])){
return json_encode(array('code'=>100,'msg'=>$res['error_msg']));
}else{
return json_encode(array('code'=>200,'data'=>$res['result'],'msg'=>''));
}
}