雖然百度你們一直在罵,可是我發現其實百度有些東西仍是能夠用的。如今你們都搞人工智能了,咱們Delphi也不能夠落後。廢話很少說,直接上代碼app
第一步,先獲取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;
最後,就是調用百度的識別服務了url
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;
這裏貼上的都是關鍵的代碼,具體的使用和免費額度,請自行百度。下面再貼一下效果圖3d