了解更多开源请访问:开源基础软件社区https://ost.51cto.com前言本来打算用九联开发板做摄像头开发实现了拍照并对图片进行AI识别的应用开发,但是遇到了一些问题。不过基于HarmonyOS的AI图像识别案例是可以正常工作的,所以我把这篇文章做成一个小分享O(∩_∩)O。概述本案例是通过网络请求连接到百度云,调用百度云AI图像识别的API,然后将结果返回给应用进行展示。百度云文档.效果图示例:文本1.创建一个项目。项目选择HarmonyOS的EmptyAbility模板,API选择8,语言选择ets。二、添加权限和导入模块1、在config.json文件中添加权限。“reqPermissions”:[{“名称”:“ohos.permission.INTERNET”}]2。在index.ets文件中导入模块,第一个是资源管理模块,第二个是网络模块。从“@ohos.resourceManager”导入资源管理器;从“@ohos.net.http”导入http;3.根据百度云API创建网络请求并传递参数。调用该接口前,需要获取access_token。具体方法见其文档(注意创建应用后需要开启图像识别服务)。定义变量@Stateaccess_token:string='HelloWorld'@StateBase64Str:string='HelloWorld'@Stateresult_description:string='description'@Stateresult_keyword:string='keyword'@Stateresult_root:string='root'@声明result_image:string='image'并将需要识别的图片上传到项目中。在这种情况下,使用莲藕的图片。写一个函数来获取access_tokenGetAccessToken(){lethttpRequest=http.createHttp();httpRequest.request(//自己替换AK和SK"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】",{方法:http.RequestMethod.POST,connectTimeout:60000,readTimeout:60000,},(err,data)=>{if(!err){让obj=JSON.parse(data.result.toString());this.access_token=obj.access_tokenconsole.info('Result1:'+data.result);console.info('Result1_token:'+this.access_token);}else{console.info('Result1_error:'+JSON.stringify(err));httpRequest.destroy();}})}写一个函数对图片进行编码,去掉编码头resourceManager.getResourceManager这个API只适用于FA模型,stage模型不适用。(所以在标准系统相机开发模式阶段,不能使用这种方式对图片进行编码)。//base64编码GetBase64(){letthat=thisresourceManager.getResourceManager((error,mgr)=>{if(error!=null){console.log("ResourceManagererroris"+error)}else{mgr.getMediaBase64($r('app.media.lianou').id,(error,value)=>{if(error!=null){console.log("base64_erroris"+error)}else{console.info('base64_result:'+value)that.Base64Str=that.getCaption(value)console.info('base64Str:'+this.Base64Str)}});}});}//去掉编码头getCaption(obj){varindex=obj.lastIndexOf("\,");obj=obj.substring(index+1,obj.length);返回对象;}写一个调用图片识别API的函数注意:这里header:{'Content-Type':'application/x-www-form-urlencoded'}将图片参数传给百度云。HTTP请求头域,默认{'Content-Type':'application/json'}。作者将同样可以在harmonyOS模拟器上运行的代码复制到一个新的openHarmony项目中,但是会报错:missingparameters。通过后台调试,发现可以接收到url的参数access_token和header参数。当header为默认类型时,可以接收到extraData中的参数,但是当header为'application/x-www-form-urlencoded'时,则无法接收到extraData中的参数。参数,所以初步认为笔者使用的OH系统版本的网络请求库不支持application/x-www-form-urlencoded参数传递。AI_request(){让httpRequest=http.createHttp();httpRequest.request("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token="+this.access_token,{method:http.RequestMethod.POST,header:{'Content-Type':'application/x-www-form-urlencoded'},extraData:{'image':this.Base64Str,'baike_num':1},connectTimeout:60000,readTimeout:60000,},(err,数据)=>{if(!err){letobj=JSON.parse(data.result.toString());this.result_description=obj.result[0].baike_info.description;this.result_keyword=obj.result[0].关键字;this.result_image=obj.result[0].baike_info.image_url;this.result_root=obj.result[0].root;console.info('Result_description:'+this.result_description)console.info('Result_keyword:'+this.result_keyword)console.info('Result_root:'+this.result_root)console.info('Result_image:'+this.result_image)}else{console.info('Result2_error:'+JSON.stringify(err));httpRequest.destroy();}})}4.编写UI界面调用函数。因为图片编码需要一定的时间,为了避免传递参数时出错,加入了一个延迟函数。build(){Column({space:10}){Button('AIrecognition').onClick(()=>{this.GetBase64()this.GetAccessToken()setTimeout(()=>{this.AI_request()},1400)})图片(this.result_image).width(150).height(150)Row({space:20}){Text(this.result_keyword).fontSize(20).width(150).height(35).textAlign(TextAlign.Start).margin(15)文本(this.result_root).fontSize(20).textAlign(TextAlign.Start).width(150).height(35).margin(15)}.width('100%').height(35)文本(this.result_description).fontSize(20).textAlign(TextAlign.Start).width('90%').height(250)}.width('100%').height('100%')}}结语以上就是本次的小分享啦!了解更多开源知识,请访问:开源基础软件社区https://ost.51cto.com。
