1. 项目简介
本项目是一个基于HarmonyOS的图像识别应用,用户可以选择图片进行植物识别,并获取识别结果。应用使用百度AI开放平台的图像识别API进行图像分析。
2. 设计思路
用户界面包含选择图片按钮、显示图片、识别按钮以及显示识别结果的文本框。
用户选择图片后,图片会显示在界面上。
用户点击识别按钮后,应用首先获取访问令牌,然后将图片转换为Base64编码,并调用百度AI的图像识别API进行识别。
最终识别结果会显示在界面上。
3. 代码实现详细解释
数据初始化
在数据初始化部分,定义了几个状态变量来存储用户输入和处理结果。
@Entry
@Component
struct Index {
@State access_token: string = '24.b838d59d269ca45a880dd3138a7eab04.2592000.1720668624.282335-81083572'
@State Base64Str: string = 'Hello World'
@State result_description: string = ''
@State result_image: string = 'image'
@State image_name:string='potato';
@State r:string='识别结果';
页面构建
在页面构建部分,定义了用户界面的布局,包括按钮和显示区域。
javascript
复制代码
onPageShow() {
const param = router.getParams();
if (param) {
console.log("Received param info:", param['info']);
this.image_name = param['info'];
console.log("Updated image_url:", this.image_name);
} else {
// 使用一个已知有效的占位符图片URL进行测试
this.image_name = 'potato';
}
}
build() {
Column({ space: 10 }) {
Button('选择图片')
.onClick(() => {
this.result_description='';
router.pushUrl({ url: 'pages/image' });
});
Image("/pages/"+this.image_name+".png")
.width(150)
.height(150)
.onError((err) => {
console.error('Image load error:', err);
console.log('Image URL:', this.image_name);
});
Button('识别')
.onClick(() => {
console.info('Button clicked');
console.log("=========="+$r('app.media.potato').id)
console.log("=========="+$r('app.media.potato').id)
this.r='正在识别中...'
this.GetAccessToken();
this.GetBase64(() => {
console.info('Base64 obtained, calling AI_request');
this.recognition();
});
});
Text(this.r)
.fontSize(20)
.textAlign(TextAlign.Start)
.width('90%')
Text(this.result_description)
.fontSize(20)
.textAlign(TextAlign.Start)
.width('90%')
.height(250);
}
.width('100%')
.height('100%');
}
选择图片
用户点击“选择图片”按钮后,应用会跳转到图片选择页面,并将选择的图片名保存到状态变量中。
javascript
复制代码
onPageShow() {
const param = router.getParams();
if (param) {
console.log("Received param info:", param['info']);
this.image_name = param['info'];
console.log("Updated image_url:", this.image_name);
} else {
// 使用一个已知有效的占位符图片URL进行测试
this.image_name = 'potato';
}
}
获取访问令牌
调用百度AI开放平台的OAuth接口获取访问令牌。
javascript
复制代码
GetAccessToken() {
let httpRequest = http.createHttp();
httpRequest.request(
"https://aip.baidubce.com/oauth/2.0/token?client_id=mpXlmuTMsl6kFbocBKmi7Ros&client_secret=p2ykY40Wj6Pmk3XKy58UF1CfR3HXBiKl&grant_type=client_credentials",
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json',
"Accept":"application/json"
},
connectTimeout: 60000,
readTimeout: 60000,
}, (err, data) => {
if (!err) {
let obj = JSON.parse(data.result.toString());
this.access_token = obj.access_token;
console.info('Access token obtained:', this.access_token);
} else {
console.error('Access token error:', JSON.stringify(err));
httpRequest.destroy();
}
});
}
获取Base64编码
从资源管理器中获取选定图片的Base64编码。
javascript
复制代码
GetBase64(callback) {
let that = this;
resourceManager.getResourceManager((error, mgr) => {
if (error != null) {
} else {
mgr.getMediaBase64ByName(this.image_name, (error, value) => {
if (error != null) {
console.error("Base64 error:", error);
} else {
console.info('Base64 result:', value);
that.Base64Str = that.getCaption(value);
console.info('Base64Str:', that.Base64Str);
if (callback) callback();
}
});
}
});
}
// 去掉编码头
getCaption(obj) {
var index = obj.lastIndexOf("\,");
obj = obj.substring(index + 1, obj.length);
return obj;
}
图像识别
将Base64编码的图片发送到百度AI的图像识别API进行识别,并处理返回结果。
javascript
复制代码
recognition() {
let httpRequest = http.createHttp();
httpRequest.request(
"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=" + this.access_token,
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
extraData: `image=${encodeURIComponent(this.Base64Str)}`, // 确保Base64字符串正确编码
connectTimeout: 60000,
readTimeout: 60000,
}, (err, data) => {
if (!err) {
try {
console.log("=================" + data.result.toString());
let obj = JSON.parse(data.result.toString());
if (obj.result && obj.result.length > 0) {
this.r='识别结果'
this.result_description = obj.result[0].name;
}
} catch (parseError) {
console.error('Failed to parse response:', parseError);
}
} else {
console.error('recognition error:', JSON.stringify(err));
}
httpRequest.destroy();
});
}
}