delphi 调用百度识别

2020-04-07 01:24:48来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

delphi 调用百度识别

虽然百度大家一直在骂,但是我发现其实百度有些东西还是可以用的。现在大家都搞人工智能了,我们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;

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

 

 

  

 

 

 

 

 

 


原文链接:https://www.cnblogs.com/wuxi15/p/12650896.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:终止 IdFtp下载

下一篇:UniGUI学习之hbox布局(33)