0%

百度AI | js 调用

这里使用 js 来调用 百度AI 接口。

这里以人体关键点为例。


调用顺序


获取 access token

首先,我们要在页面上建一个应用。

然后进入应用管理界面,拿到相关的 key 和 secret。

根据

获得相应的 access token

相应的请求如下

1
2
3
4
5
6
7
8
const getToken = () => {
axios.post("/api/oauth/2.0/token?grant_type=client_credentials&client_id=你的key&client_secret=你的secret",).then(function (response) {
console.log(response);
return response;
}).catch(function (error) {
return error
})
}

单纯的上面的 js 获取不到,因为有跨域问题,所以,请参考下面的文章解决跨域问题。

如果要部署到服务器的话,可以参考 nginx 的跨域。

获取 关键点信息

这里直接贴一下相关的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function image2Base64(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
return canvas.toDataURL();
}

import img_pose from "../../images/3.jpg"

$("#button").click(function () {

let base64 = "";
let img = new Image();
img.src = img_pose;
img.onload = function () {
base64 = image2Base64(img).substring(22,);

$.ajax({
url: "/api/rest/2.0/image-classify/v1/body_analysis?access_token=你的token",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: {
image: base64,
},
success: function (res) {
console.log(res["person_info"][0]["body_parts"]);
}
});
}
});

关于人体关键点比较的更多技术细节请参考下面的博文。

这里有一个非常神奇的事情,假如将上面的 ajax 调用,换成 axios 就会返回

{log_id: 8274052707199542000, error_code: 216101, error_msg: "param image not exist"}

可能是我调用 axios 的方式不对,我这里也贴一下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function image2Base64(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
return canvas.toDataURL();
}

import img_pose from "../../images/3.jpg"

$("#button").click(function () {

let base64 = "";
let img = new Image();
img.src = img_pose;
img.onload = function () {
base64 = image2Base64(img).substring(22,);
axios.post("/api/rest/2.0/image-classify/v1/body_analysis?access_token=24.1fcd80c3545992ac3c1292c72428d9cf.2592000.1612759019.282335-23518176", {
image: base64,
}, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(function (response) {
console.log(response.data);
console.log(123);e
}).catch(function (error) {
console.log(error);
})
}
});
请我喝杯咖啡吧~