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;

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

 

 

  

 

 

 

 

 

 

posted @ 2020-04-07 01:30  似水@流年  阅读(265)  评论(1编辑  收藏
悠悠记得当天笑 仿佛入迷 又带一点惘 种种喜悦 令人为你鼓掌 眉飞色舞千千样 你是个妙人 是个少年狂