首先,需要安装requests和base64这两个Python库。可以使用以下命令进行安装:
pip install requests
pip install base64
然后,使用以下代码访问百度图片识别API,并进行图片识别:
import requests
import base64
# 设置百度AI的API Key和Secret Key
API_KEY = ‘你的API Key’
SECRET_KEY = ‘你的Secret Key’
# 获取Access Token
TOKEN_URL = ‘https://aip.baidubce.com/oauth/2.0/token’
token_params = {
‘grant_type’: ‘client_credentials’,
‘client_id’: API_KEY,
‘client_secret’: SECRET_KEY
}
r = requests.post(TOKEN_URL, data=token_params)
access_token = r.json()[‘access_token’]
# 读取要识别的图片
with open(‘test.jpg’, ‘rb’) as f:
img = base64.b64encode(f.read())
# 构建请求体
request_url = ‘https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general’
headers = {‘Content-Type’: ‘application/x-www-form-urlencoded’}
params = {‘access_token’: access_token}
data = {‘image’: img}
# 发送请求
response = requests.post(url=request_url, headers=headers, params=params, data=data)
# 处理响应结果
if response.status_code == 200:
results = response.json()[‘result’]
for result in results:
print(result[‘keyword’], result[‘score’])
else:
print(‘请求失败’)
其中,API_KEY和SECRET_KEY需要替换为你在百度AI平台上申请的对应密钥。test.jpg需要替换为你要识别的图片文件名。代码执行完成后,会输出识别结果,包括关键词和置信度。
注意:使用百度AI平台需要先注册百度账号并开通AI服务,且需要按照平台的要求进行密钥申请和权限设置。此外,本例中使用的是图片通用识别API,不同的API请求地址、请求参数和响应格式可能会有所不同,请根据需要进行修改
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class BaiduImageRecognition {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// 设置请求参数
File file = new File(“test.jpg”);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(“image”, file.getName(),
RequestBody.create(MediaType.parse(“image/jpeg”), file))
.addFormDataPart(“access_token”, “your-access-token”)
.build();
// 发送POST请求
Request request = new Request.Builder()
.url(“https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general”)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
// 解析响应结果
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.err.println(“请求失败,响应码:” + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意替换代码中的图片文件名和API访问令牌(access_token)。