Baidu Image Recognition API

Preview the effect first

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

As can be seen from the above preview image, each picture recognizes 5 pieces of data , and each piece of data is arranged from high to low according to the degree of recognition , and each piece of data includes the item name , degree of recognition , and category

Preparation

1. Register a Baidu account

2. Log in to Baidu Smart Cloud Console

3. In the product list, find artificial intelligence -> image recognition

4. Click Create Application, as shown in the figure below:

Created application list

code part

1. Get access_token value

Note : The access_token value is required to use image recognition, so it needs to be obtained first, so that the following code can be used

There are many ways to obtain access_token. Here, use PHP to obtain it. For more methods and instructions on obtaining access_token, please refer to the official document:

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

Create a get_token.php file to get access_token value

PHP get access_token code example:

 
 

php

copy code

<?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); ?>

The returned data is as follows, the red box is the access_token value we want

2. Image upload and recognition

2.1. Create an upload folder in the root directory of the project to store uploaded pictures

2.2. Create an index.html file for uploading pictures and data rendering

code show as below:

 
 

js

copy code

<!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. Create an upload.php file to receive pictures and call image recognition API

Remarks : There are various Baidu image recognition API interfaces, here is the [ General Object and Scene Recognition Advanced Edition]  ; this interface supports the recognition of 100,000 common objects and scenes, the interface returns the name results of major categories and subcategories, and supports Get the encyclopedia information corresponding to the image recognition result

There are also many ways to call this interface. Here, PHP is used to call the interface. For more methods and instructions on calling the advanced version of general object and scene recognition , please refer to the official document:

ai.baidu.com/docs#/Image…

Sample PHP request code:

 
 

php

copy code

<?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;  //将识别的数据输出到前端 ?>

Epilogue Supplement

In the actual development process, the access_token value is not written as a separate page file, but written in the configuration of the project system; since the access_token value is valid for 30 days, you can re-request the access_token value by judging whether it is invalid

Guess you like

Origin blog.csdn.net/bruce__ray/article/details/131144536