一、登录百度AI开放平台创建orc应用
选择图像识别
→创建应用
创建好的应用:
二、下载sdk包
我演示的是php的:https://ai.baidu.com/sdk#ocr
三、tp框架引入sdk包
我在最外层新建了一个Ocr下载好的sdk包放入到vendor第三方类库里面:
四、代码实现
控制器里:
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
if(isset($_POST['sub']))
{
$token=$this->curl("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxxx&client_secret=xxxxxxxx");
$token=json_decode($token,true);
$token=$token['access_token']; //获取token
$image = 'http://www.people.com.cn/mediafile/pic/20130530/74/8789617213943725442.jpg'; //用户上传的图片
$app_id="xxxxxx"; //你的appid
$api_key="xxxxxx"; //你的api_key
$secret_key="xxxxxx"; //你的secret_key
vendor('Ocr.AipOcr'); //类库引入
$client = new \AipOcr($app_id,$api_key,$secret_key); //实例化AipOcr类
// 如果有可选参数
$options = array();
$options["language_type"] = "CHN_ENG";
$options["detect_direction"] = "false";
$options["detect_language"] = "false";
$options["probability"] = "false";
$options["access_token"]=$token; //获取token
// 带参数调用通用文字识别, 图片参数为远程url图片
$data = $client->basicGeneralUrl($image, $options); //调用通用文字识别接口
print_r($data);die;
}
else
return $this->fetch('index');
}
public function curl($url,$postData=[],$headers=[]){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url); //要访问的地址
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //执行结果是否被返回,0返,1不返
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
if($postData){
curl_setopt($ch,CURLOPT_TIMEOUT,60);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postData);
}
if(curl_exec($ch)==false){
$data='';
}
else{
$data=curl_multi_getcontent($ch);
}
curl_close($ch);javascript:;
return $data;
}
}
五、效果展示
这是需要识别的图片: