百度图像识别 API

首先预览下效果

feaa250077a543a39f037ae8e78a3e80~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp (640×594) (byteimg.com)

从以上预览图中可看出,每张图片识别出5条数据,每条数据根据识别度从高往下排,每条数据包含物品名称识别度所属类目

准备工作

1、注册百度账号

2、登录百度智能云控制台

3、在产品列表中找到 人工智能->图像识别

4、点击创建应用,如下图:

已创建好的应用列表

代码部分

1、获取access_token值

注意:使用图像识别需用到access_token值,因此需先获取到,以便下面代码的使用

access_token获取的方法有多种,这里使用PHP获取,更多有关access_token获取的方法以及说明可查看官方文档:

ai.baidu.com/docs#/Auth/…

创建一个get_token.php文件,用来获取access_token值

PHP获取access_token代码示例:

 
 

php

复制代码

<?php //请求获取access_token值函数 function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $curl = curl_init();//初始化curl curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($curl, CURLOPT_HEADER, 0);//设置header curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($curl, CURLOPT_POST, 1);//post提交方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $data = curl_exec($curl);//运行curl curl_close($curl); return $data; } $url = 'https://aip.baidubce.com/oauth/2.0/token'; //固定地址 $post_data['grant_type'] = 'client_credentials'; //固定参数 $post_data['client_id'] = '你的 Api Key'; //创建应用的API Key; $post_data['client_secret'] = '你的 Secret Key'; //创建应用的Secret Key; $o = ""; foreach ( $post_data as $k => $v ) { $o.= "$k=" . urlencode( $v ). "&" ; } $post_data = substr($o,0,-1); $res = request_post($url, $post_data);//调用获取access_token值函数 var_dump($res); ?>

返回的数据如下,红框内的就是我们所要的access_token值

2、图片上传及识别

2.1、在项目的根目录下创建一个upload文件夹,用于存放上传的图片

2.2、创建一个index.html文件,用于上传图片及数据渲染

代码如下:

 
 

js

复制代码

<!DOCTYPE html> <html> <head> <meta charset="utf-8">  <title>使用百度 API 实现图像识别</title>  <style type="text/css">   .spanstyle{     display:inline-block;     width:500px;     height:500px;     position: relative;   } </style> <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> <script>   function imageUpload(imgFile) {     var uploadfile= imgFile.files[0]  //获取图片文件流     var formData = new FormData();    //创建一个FormData对象     formData.append('file',uploadfile);     //将图片放入FormData对象对象中(由于图片属于文件格式,不能直接将文件流直接通过ajax传递到后台,需要放入FormData对象中。在传递)     $("#loading").css("opacity",1);      $.ajax({           type: "POST",       //POST请求           url: "upload.php",  //接收图片的地址(同目录下的php文件)           data:formData,      //传递的数据           dataType:"json",    //声明成功使用json数据类型回调           //如果传递的是FormData数据类型,那么下来的三个参数是必须的,否则会报错           cache:false,  //默认是true,但是一般不做缓存           processData:false, //用于对data参数进行序列化处理,这里必须false;如果是true,就会将FormData转换为String类型           contentType:false,  //一些文件上传http协议的关系,自行百度,如果上传的有文件,那么只能设置为false          success: function(msg){  //请求成功后的回调函数               console.log(msg.result)               //预览上传的图片               var filereader = new FileReader();               filereader.onload = function (event) {                   var srcpath = event.target.result;                   $("#loading").css("opacity",0);                   $("#PreviewImg").attr("src",srcpath);                 };               filereader.readAsDataURL(uploadfile);                 //将后台返回的数据进行进一步处理                 var data=  '<li style="margin:2% 0"><span>物品名称:'+msg.result[0].keyword+';</span> <span style="padding: 0 2%">识别度:'+msg.result[0].score*100+'%'+';</span><span>所属类目:'+msg.result[0].root+';</span></li>'                 data=data+  '<li style="margin:2% 0"><span>物品名称:'+msg.result[1].keyword+';</span> <span style="padding: 0 2%">识别度:'+msg.result[1].score*100+'%'+';</span><span>所属类目:'+msg.result[1].root+';</span></li>'                 data=data+  '<li style="margin:2% 0"><span>物品名称:'+msg.result[2].keyword+';</span> <span style="padding: 0 2%">识别度:'+msg.result[2].score*100+'%'+';</span><span>所属类目:'+msg.result[2].root+';</span></li>'                 data=data+  '<li style="margin:2% 0"><span>物品名称:'+msg.result[3].keyword+';</span> <span style="padding: 0 2%">识别度:'+msg.result[3].score*100+'%'+';</span><span>所属类目:'+msg.result[3].root+';</span></li>'                 data=data+  '<li style="margin:2% 0"><span>物品名称:'+msg.result[4].keyword+';</span> <span style="padding: 0 2%">识别度:'+msg.result[4].score*100+'%'+';</span><span>所属类目:'+msg.result[4].root+';</span></li>'                 //将识别的数据在页面渲染出来                $("#content").html(data);         }   });    } </script> </head> <body>   <fieldset>      <input type="file"  onchange="imageUpload(this)" >      <legend>图片上传</legend>   </fieldset> <div style="margin-top:2%">     <span class="spanstyle">       <img id="PreviewImg" src="default.jpg" style="width:100%;max-height:100%"  >       <img id="loading" style="width:100px;height:100px;top: 36%;left: 39%;position: absolute;opacity: 0;" src="loading.gif" >     </span>     <span class="spanstyle" style="vertical-align: top;border: 1px dashed #ccc;background-color: #4ea8ef;color: white;">         <h4 style="padding-left:2%">识别结果:</h4>         <ol style="padding-right: 20px;" id="content">         </ol>     </span> </div> </body> </html>

2.3、创建一个upload.php文件,用于接收图片及调用图像识别API

备注:百度图像识别API接口有多种,这里使用的是【通用物体和场景识别高级版】 ;该接口支持识别10万个常见物体及场景,接口返回大类及细分类的名称结果,且支持获取图片识别结果对应的百科信息

该接口调用的方法也有多种,这里使用PHP来调用接口,更多有关通用物体和场景识别高级版调用的方法以及说明可查看官方文档:

ai.baidu.com/docs#/Image…

PHP请求代码示例:

 
 

php

复制代码

<?php         //图像识别请求函数             function request_post($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;         }         $temp = explode(".", $_FILES["file"]["name"]);         $extension = end($temp);     // 获取图片文件后缀名         $_FILES["file"]["name"]=time().'.'.$extension;//图片重命名(以时间戳来命名)         //将图片文件存在项目根目录下的upload文件夹下         move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);         $token = '调用鉴权接口获取的token';//将获取的access_token值放进去         $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=' . $token;         $img = file_get_contents("upload/" . $_FILES["file"]["name"]);//本地文件路径(存入后的图片文件路径)         $img = base64_encode($img);//文件进行base64编码加密         //请求所需要的参数         $bodys = array(             'image' => $img,//Base64编码字符串             'baike_num'=>5  //返回百科信息的结果数 5条         );         $res = request_post($url, $bodys);//调用请求函数         echo $res;  //将识别的数据输出到前端 ?>

结语补充

在实际开发过程中,获取access_token值并不是单独写成一个页面文件,而是写在项目系统的配置中;由于access_token值有效期为30天,可通过判断是否失效,来重新请求access_token值

猜你喜欢

转载自blog.csdn.net/bruce__ray/article/details/131144536