var
i, X, Y: DWORD;
fLibrary: HMODULE;
fModel: Pointer;
fInterpreterOptions: Pointer;
fInterpreter: Pointer;
fStatus: TfLiteStatus;
fInputTensorCount, fOutputTensorCount, fNumDims: Int32;
fInputTensor, fOutputTensor: Pointer;
fInputDims: Integer;
fTensorName: PAnsiChar;
fTensorType: TfLiteType;
fTensorByteSize: SIZE_T;
fInput: array [0 .. 28 * 28 - 1] of Float32;
fOutput: array [0 .. 10 - 1] of Float32;
fValue: Extended;
begin
fLibrary := LoadLibrary(LibraryName);
if fLibrary = 0 then
begin
ShowMessage('Error: Load tensorflow lite library ' + LibraryName + ' - ' +
SysErrorMessage(GetLastError));
Exit;
end;
try
fModel := TfLiteModelCreateFromFile(PAnsiChar(AnsiString(Edit1.Text)));
if fModel = nil then
begin
ShowMessage('Error: Create model from file - ' +
SysErrorMessage(GetLastError));
Exit;
end;
fInterpreterOptions := TfLiteInterpreterOptionsCreate;
if fInterpreterOptions <> nil then
begin
TfLiteInterpreterOptionsSetNumThreads(fInterpreterOptions, 2);
fInterpreter := TfLiteInterpreterCreate(fModel, fInterpreterOptions);
TfLiteInterpreterOptionsDelete(fInterpreterOptions);
TfLiteModelDelete(fModel);
if fInterpreter <> nil then
begin
fStatus := TfLiteInterpreterAllocateTensors(fInterpreter);
fInputTensorCount := TfLiteInterpreterGetInputTensorCount(fInterpreter);
fOutputTensorCount := TfLiteInterpreterGetOutputTensorCount
(fInterpreter);
fInputTensor := TfLiteInterpreterGetInputTensor(fInterpreter, 0);
fOutputTensor := TfLiteInterpreterGetOutputTensor(fInterpreter, 0);
if fInputTensor <> nil then
begin
fTensorByteSize := TfLiteTensorByteSize(fInputTensor);
for Y := 0 to Image1.Picture.Bitmap.Height - 1 do
begin
for X := 0 to Image1.Picture.Bitmap.Width - 1 do
begin
if (Image1.Canvas.Pixels[X, Y] > 0) then
fInput[X + (Y * Image1.Picture.Bitmap.Width)] := 1
else
fInput[X + (Y * Image1.Picture.Bitmap.Width)] := 0;
end;
end;
fStatus := TfLiteTensorCopyFromBuffer(fInputTensor, @fInput,
fTensorByteSize);
fStatus := TfLiteInterpreterInvoke(fInterpreter);
if fStatus = kTfLiteOk then
begin
for i := 0 to High(fOutput) do
fOutput[i] := 0;
fOutputTensor := TfLiteInterpreterGetOutputTensor(fInterpreter, 0);
fTensorByteSize := TfLiteTensorByteSize(fOutputTensor);
if fOutputTensor <> nil then
begin
fStatus := TfLiteTensorCopyToBuffer(fOutputTensor, @fOutput,
fTensorByteSize);
if fStatus = kTfLiteOk then
begin
ListView1.Items.Clear;
for i := 0 to Length(fOutput) - 1 do
begin
fValue := StrToFloat(Copy(FloatToStr(fOutput[i]), 1, 17));
if fValue <= 1 then
begin
with ListView1.Items.Add do
begin
Caption := FloatToStrF(fValue, ffNumber, 17, 17);
SubItems.Add(IntToStr(i));
end;
end;
end;
ListView1.AlphaSort;
Beep;
end;
end;
end;
end;
end;
end;
finally
FreeLibrary(fLibrary);
end;