safari浏览器formdata未识别类型_使用百度 API 实现图像识别

ed206e14ed2700bf806294d169356da7.gif

闲来无事研究了百度图像识别 API,发现该功能还算强大,在此将其使用方法总结成教程,提供大家学习参考

首先预览下效果


eeec1f3b29bcb9a80e5a44b2f8630c5e.gif

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

准备工作


1、注册百度账号

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

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

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

3121892cc709be99261b0e6ef24ab99f.png

cd03a21d1f8ab7f864c1713610023fc0.png

99a327fb61da551c97f4b495c80ac1bd.png

已创建好的应用列表

代码部分


1、获取access_token值

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

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

http://ai.baidu.com/docs#/Auth/top

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

PHP获取access_token代码示例:

<?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值

0ff24c63a1880264d2fec4b7ae13067d.png

2、图片上传及识别

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

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

代码如下:

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=  '物品名称:'+msg.result[0].keyword+'; 识别度:'+msg.result[0].score*100+'%'+';所属类目:'+msg.result[0].root+';'
                data=data+  '物品名称:'+msg.result[1].keyword+'; 识别度:'+msg.result[1].score*100+'%'+';所属类目:'+msg.result[1].root+';'
                data=data+  '物品名称:'+msg.result[2].keyword+'; 识别度:'+msg.result[2].score*100+'%'+';所属类目:'+msg.result[2].root+';'
                data=data+  '物品名称:'+msg.result[3].keyword+'; 识别度:'+msg.result[3].score*100+'%'+';所属类目:'+msg.result[3].root+';'
                data=data+  '物品名称:'+msg.result[4].keyword+'; 识别度:'+msg.result[4].score*100+'%'+';所属类目:'+msg.result[4].root+';'//将识别的数据在页面渲染出来
               $("#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来调用接口,更多有关通用物体和场景识别高级版调用的方法以及说明可查看官方文档:

http://ai.baidu.com/docs#/ImageClassify-API/141c7bfa

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值

END

51262bc81b24e0e9dfb2d61e61159996.png

我就知道你“在看” 282d13ddc6b96903814e4f52cf83504b.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值