• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow_lite_support/cc/task/core/task_utils.h"
17 
18 #include <fstream>
19 
20 #include "absl/strings/str_cat.h"
21 
22 namespace tflite {
23 namespace task {
24 namespace core {
25 
Dequantize(const TfLiteTensor & tensor,int index)26 double Dequantize(const TfLiteTensor& tensor, int index) {
27   int32_t quantized_value = 0;
28   switch (tensor.type) {
29     case kTfLiteUInt8:
30       quantized_value = GetTensorData<uint8_t>(&tensor)[index];
31       break;
32     case kTfLiteInt8:
33       quantized_value = GetTensorData<int8_t>(&tensor)[index];
34       break;
35     case kTfLiteInt16:
36       quantized_value = GetTensorData<int16_t>(&tensor)[index];
37       break;
38     default:
39       TF_LITE_FATAL(
40           absl::StrCat(
41               "Invalid tensor type for dequantization ", tensor.name,
42               ". Requested kTfLiteUInt8, kTfLiteInt8 or kTfLiteInt16, got ",
43               TfLiteTypeGetName(tensor.type), ".")
44               .c_str());
45   }
46   return tensor.params.scale * (quantized_value - tensor.params.zero_point);
47 }
48 
GetStringAtIndex(const TfLiteTensor * labels,int index)49 std::string GetStringAtIndex(const TfLiteTensor* labels, int index) {
50   const auto& strref = tflite::GetString(labels, index);
51   return std::string(strref.str, strref.len);
52 }
53 
LoadBinaryContent(const char * filename)54 std::string LoadBinaryContent(const char* filename) {
55   std::ifstream input_file(filename, std::ios::binary | std::ios::ate);
56   // Find buffer size from input file, and load the buffer.
57   size_t buffer_size = input_file.tellg();
58   std::string buffer(buffer_size, '\0');
59   input_file.seekg(0, std::ios::beg);
60   input_file.read(const_cast<char*>(buffer.c_str()), buffer_size);
61   return buffer;
62 }
63 
64 }  // namespace core
65 }  // namespace task
66 }  // namespace tflite
67