基于百度云的物体识别

2019-06-10  本文已影响0人  页川叶川
  • 从前有一群人,他们几乎不自己通过代码实现功能,而是沉迷于地调用各种API,实现各种惊天地泣鬼神的功能,江湖美名曰:调库小王子。哎呀真香啊!
  • 好了,不扯闲话。由于最近同学的项目有物体识别的需求,但这并不不是我们学习的方向,因此我们只需要简单了解并使用百度云提供的物体识别API即可,这里我使用了Python以及Java两种编程语言实现了物体识别API的调用,读者可以参考参考。

Let's go,上代码:

1.Python

1.获取access_token

import ssl
import json

def demo():
    client_id = "从百度云上获取"
    client_secret = "从百度云上获取"

    host = 'https://aip.baidubce.com/oauth/2.0/token?' \
           'grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret

    request = urlReq.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urlReq.urlopen(request)
    content = response

    json_data = json.load(content)
    accessToken = json_data.get("access_token")
    if (accessToken):
        return accessToken

2.重头戏:图像识别

# encoding:utf-8
import base64
import urllib,urllib.request as urlReq
import Access_token
import json

'''
动物识别
'''

# 动物识别API请求URL
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"

# 二进制方式打开图片文件  r:只读方式打开   b:二进制打开
f = open('F:\Google下载\/aaa.jpg', 'rb')

# 将文件进行base64编码
img = base64.b64encode(f.read())

# 将image信息封装成传输参数
params = {"image":img,"top_num":6}
params = urllib.parse.urlencode(params).encode("utf-8")

# 通过Access_token.py文件获取到access_token
access_token = Access_token.demo()

# 最终发出请求的URL
request_url = request_url + "?access_token=" + access_token
request = urlReq.Request(url=request_url, data=params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
response = urlReq.urlopen(request)
content = response

json_data = json.load(content)
result = json_data.get("result")[0]   #这里返回的是一个map

name = result['name']     #通过map的key获取value
if content:
    print("识别结果: " + name)

2.Java

1.下载百度云提供的工具类

/**
    * 重要提示代码中所需工具类
    * FileUtil,Base64Util,HttpUtil,GsonUtils请从
    * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
    * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
    * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
    * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
    * 下载
    */

2.xml文件导入相关依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

3.获取access_token

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

public class AuthService {

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getToken() {

        String client_id = "从百度云上获取";
        String client_secret = "从百度云上获取";
        String access_token = "none";

        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret)
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (!response.isSuccessful()) {
                result = "服务器端错误: " + response;
            }

            // 将结果转化为json格式
            JSONObject jsonpObject = new JSONObject(result);
            // 获取access_token
            access_token = jsonpObject.getString("access_token");

            return access_token;
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return null;
    }

}

4.重头戏:图像识别

import org.json.JSONObject;
import com.wss.demo.auxiliary.Base64Util;
import com.wss.demo.auxiliary.FileUtil;
import com.wss.demo.auxiliary.HttpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.sql.ResultSet;

@RestController
public class TestController {

    private String accessToken = "";

    @RequestMapping("/animal")
    @ResponseBody
    public String animal() {
        // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
        accessToken = AuthService.getToken();

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
        try {
            // 本地文件路径
            String filePath = "F:/Google下载/aaa.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam + "&top_num=" + 6;

            String result = HttpUtil.post(url, accessToken, param);

            JSONObject json = new JSONObject(result);
            JSONObject answer = (JSONObject) json.getJSONArray("result").get(0);

            return answer.getString("name");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
上一篇下一篇

猜你喜欢

热点阅读