当前位置: 移动技术网 > IT编程>开发语言>Delphi > delphi 调用百度识别

delphi 调用百度识别

2020年04月07日  | 移动技术网IT编程  | 我要评论

虽然百度大家一直在骂,但是我发现其实百度有些东西还是可以用的。现在大家都搞人工智能了,我们delphi也不可以落后。废话不多说,直接上代码

第一步,先获取accesstoken

function getaccesstoken(const client_id, client_secret: string;
  http: tnethttpclient;out access_token,expires_in,error:string):boolean;
var
 url:string;
 cparam:tstringlist;
 fjson:tjsonobject;
 s:string;
begin
  url:='https://aip.baidubce.com/oauth/2.0/token';
  cparam:=tstringlist.create;
  cparam.add('grant_type=client_credentials');
  cparam.add('client_id='+client_id);
  cparam.add('client_secret='+client_secret);
  try
  s:=http.post(url,cparam).contentasstring;
  fjson:=tjsonobject.parsejsonvalue(s) as tjsonobject;
  error:='';
  if fjson.values['error']<>nil then
   begin
     if fjson.values['error_description'].value='unknown client id' then
       error:='api key不正确';
     if fjson.values['error_description'].value='client authentication failed' then
       error:='secret key不正确';
     if error='' then
       error:='未知错误';
       fjson.free;
     exit(false);
   end;
    access_token:=fjson.values['access_token'].value;
    expires_in:=fjson.values['expires_in'].value;
    result:=true;
    fjson.free;
  finally
    cparam.clear;
    cparam.free;
  end;
end;

  第二步,将我们要识别的图片进行编码

function imagetobase64(image:tstream):string;
var
 fstream:tstringstream;
begin
 fstream:=tstringstream.create;
 tbase64encoding.base64.encode(image,fstream);
 fstream.position:=0;
 result:=turlencoding.url.encode(fstream.datastring);
end;

  最后,就是调用百度的识别服务了

function getorc(image:tstream;http: tnethttpclient;const access_token:string):string;
var
  cimage:string;
  url:string;
  cparam:tstringstream;
  cstr:tstringlist;
  jo:tjsonobject;
  ja:tjsonarray;
  jv:tjsonvalue;
begin

  cimage:=imagetobase64(image);
//  url:='https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token='+access_token;
  url:='https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token='+access_token;
  http.contenttype:='application/x-www-form-urlencoded;charset=utf-8';
  cparam:= tstringstream.create;
  cstr:=tstringlist.create;
  cstr.add('image='+cimage);
  cstr.add('detect_direction=true');
  cstr.delimiter:='&';
  cparam.writestring(cstr.delimitedtext);
  cstr.free;
  cparam.position:=0;
  result:=http.post(url,cparam).contentasstring();
  jo:=tjsonobject.parsejsonvalue(result) as tjsonobject;
  if jo.values['error_code']<>nil then
    begin
      result:=jo.values['error_code'].value+','+jo.values['error_msg'].value;
      exit;
    end;
  ja:=jo.values['words_result'] as tjsonarray;
  result:='';
  for jv in ja do
    result:=result+jv.p['words'].value;

//  result:=ja.tostring;
  cparam.free;

end;

  这里贴上的都是关键的代码,具体的使用和免费额度,请自行百度。下面再贴一下效果图

 

 

  

 

 

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网