|
| 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/vision/image_transformer.h" |
| 17 | + |
| 18 | +#include "external/com_google_absl/absl/algorithm/container.h" |
| 19 | +#include "external/com_google_absl/absl/strings/str_format.h" |
| 20 | +#include "external/com_google_absl/absl/strings/string_view.h" |
| 21 | +#include "flatbuffers/flatbuffers.h" // from @flatbuffers |
| 22 | +#include "tensorflow_lite_support/cc/common.h" |
| 23 | +#include "tensorflow_lite_support/cc/port/integral_types.h" |
| 24 | +#include "tensorflow_lite_support/cc/port/status_macros.h" |
| 25 | +#include "tensorflow_lite_support/cc/task/core/task_api_factory.h" |
| 26 | +#include "tensorflow_lite_support/cc/task/core/task_utils.h" |
| 27 | +#include "tensorflow_lite_support/cc/task/core/tflite_engine.h" |
| 28 | +#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_utils.h" |
| 29 | +#include "tensorflow_lite_support/metadata/cc/metadata_extractor.h" |
| 30 | +#include "tensorflow_lite_support/metadata/metadata_schema_generated.h" |
| 31 | + |
| 32 | +namespace tflite { |
| 33 | +namespace task { |
| 34 | +namespace vision { |
| 35 | + |
| 36 | +namespace { |
| 37 | + |
| 38 | +using ::absl::StatusCode; |
| 39 | +using ::tflite::metadata::ModelMetadataExtractor; |
| 40 | +using ::tflite::support::CreateStatusWithPayload; |
| 41 | +using ::tflite::support::StatusOr; |
| 42 | +using ::tflite::support::TfLiteSupportStatus; |
| 43 | +using ::tflite::task::core::AssertAndReturnTypedTensor; |
| 44 | +using ::tflite::task::core::TaskAPIFactory; |
| 45 | +using ::tflite::task::core::TfLiteEngine; |
| 46 | + |
| 47 | +} // namespace |
| 48 | + |
| 49 | +/* static */ |
| 50 | +StatusOr<std::unique_ptr<ImageTransformer>> ImageTransformer::CreateFromOptions( |
| 51 | + const ImageTransformerOptions& options, |
| 52 | + std::unique_ptr<tflite::OpResolver> resolver) { |
| 53 | + RETURN_IF_ERROR(SanityCheckOptions(options)); |
| 54 | + |
| 55 | + // Copy options to ensure the ExternalFile outlives the constructed object. |
| 56 | + auto options_copy = absl::make_unique<ImageTransformerOptions>(options); |
| 57 | + |
| 58 | + std::unique_ptr<ImageTransformer> image_transformer; |
| 59 | + //TODO: Should be model_file_with_metadata? |
| 60 | + if (options_copy->base_options().has_model_file()) { |
| 61 | + ASSIGN_OR_RETURN( |
| 62 | + image_classifier, |
| 63 | + TaskAPIFactory::CreateFromExternalFileProto<ImageTransformer>( |
| 64 | + &options_copy->model_file_with_metadata(), std::move(resolver), |
| 65 | + options_copy->num_threads(), options_copy->compute_settings())); |
| 66 | + } else if (options_copy->base_options().has_model_file()) { |
| 67 | + ASSIGN_OR_RETURN(image_classifier, |
| 68 | + TaskAPIFactory::CreateFromBaseOptions<ImageTransformer>( |
| 69 | + &options_copy->base_options(), std::move(resolver))); |
| 70 | + } else { |
| 71 | + // Should never happen because of SanityCheckOptions. |
| 72 | + return CreateStatusWithPayload( |
| 73 | + StatusCode::kInvalidArgument, |
| 74 | + absl::StrFormat("Expected exactly one of `base_options.model_file` or " |
| 75 | + "`model_file_with_metadata` to be provided, found 0."), |
| 76 | + TfLiteSupportStatus::kInvalidArgumentError); |
| 77 | + } |
| 78 | + |
| 79 | + RETURN_IF_ERROR(image_transformer->Init(std::move(options_copy))); |
| 80 | + |
| 81 | + return image_transformer; |
| 82 | +} |
| 83 | + |
| 84 | +/* static */ |
| 85 | +absl::Status ImageTransformer::SanityCheckOptions( |
| 86 | + const ImageTransformerOptions& options) { |
| 87 | + int num_input_models = (options.base_options().has_model_file() ? 1 : 0) + |
| 88 | + (options.has_model_file_with_metadata() ? 1 : 0); |
| 89 | + |
| 90 | + if (num_input_models != 1) { |
| 91 | + return CreateStatusWithPayload( |
| 92 | + StatusCode::kInvalidArgument, |
| 93 | + absl::StrFormat("Expected exactly one of `base_options.model_file` or " |
| 94 | + "`model_file_with_metadata` to be provided, found %d.", |
| 95 | + num_input_models), |
| 96 | + TfLiteSupportStatus::kInvalidArgumentError); |
| 97 | + } |
| 98 | + if (options.base_options().compute_settings().tflite_settings().cpu_settings().num_threads() == 0 || |
| 99 | + options.base_options().compute_settings().tflite_settings().cpu_settings().num_threads() < -1) { |
| 100 | + return CreateStatusWithPayload( |
| 101 | + StatusCode::kInvalidArgument, |
| 102 | + "`num_threads` must be greater than 0 or equal to -1.", |
| 103 | + TfLiteSupportStatus::kInvalidArgumentError); |
| 104 | + } |
| 105 | + return absl::OkStatus(); |
| 106 | +} |
| 107 | + |
| 108 | +absl::Status ImageTransformer::Init( |
| 109 | + std::unique_ptr<ImageTransformerOptions> options) { |
| 110 | + // Set options. |
| 111 | + options_ = std::move(options); |
| 112 | + |
| 113 | + // Perform pre-initialization actions (by default, sets the process engine for |
| 114 | + // image pre-processing to kLibyuv as a sane default). |
| 115 | + RETURN_IF_ERROR(PreInit()); |
| 116 | + |
| 117 | + // Sanity check and set inputs and outputs. |
| 118 | + RETURN_IF_ERROR(CheckAndSetInputs()); |
| 119 | + RETURN_IF_ERROR(CheckAndSetOutputs()); |
| 120 | + |
| 121 | + RETURN_IF_ERROR(PostInit()); |
| 122 | + |
| 123 | + return absl::OkStatus(); |
| 124 | +} |
| 125 | + |
| 126 | +absl::Status ImageTransformer::PreInit() { |
| 127 | + SetProcessEngine(FrameBufferUtils::ProcessEngine::kLibyuv); |
| 128 | + return absl::OkStatus(); |
| 129 | +} |
| 130 | + |
| 131 | +absl::Status ImageTransformer::PostInit() { |
| 132 | + // Nothing to do. |
| 133 | + return absl::OkStatus(); |
| 134 | +} |
| 135 | + |
| 136 | +absl::Status ImageTransformer::CheckAndSetOutputs() { |
| 137 | + // First, sanity checks on the model itself. |
| 138 | + const TfLiteEngine::Interpreter* interpreter = |
| 139 | + GetTfLiteEngine()->interpreter(); |
| 140 | + |
| 141 | + // Check the number of output tensors. |
| 142 | + if (TfLiteEngine::OutputCount(interpreter) != 1) { |
| 143 | + return CreateStatusWithPayload( |
| 144 | + StatusCode::kInvalidArgument, |
| 145 | + absl::StrFormat("Image segmentation models are expected to have only 1 " |
| 146 | + "output, found %d", |
| 147 | + TfLiteEngine::OutputCount(interpreter)), |
| 148 | + TfLiteSupportStatus::kInvalidNumOutputTensorsError); |
| 149 | + } |
| 150 | + |
| 151 | + const TfLiteTensor* output_tensor = TfLiteEngine::GetOutput(interpreter, 0); |
| 152 | + |
| 153 | + // Check tensor dimensions. |
| 154 | + if (output_tensor->dims->size != 4) { |
| 155 | + return CreateStatusWithPayload( |
| 156 | + StatusCode::kInvalidArgument, |
| 157 | + absl::StrFormat( |
| 158 | + "Output tensor is expected to have 4 dimensions, found %d.", |
| 159 | + output_tensor->dims->size), |
| 160 | + TfLiteSupportStatus::kInvalidOutputTensorDimensionsError); |
| 161 | + } |
| 162 | + |
| 163 | + if (output_tensor->dims->data[0] != 1) { |
| 164 | + return CreateStatusWithPayload( |
| 165 | + StatusCode::kInvalidArgument, |
| 166 | + absl::StrFormat("Expected batch size of 1, found %d.", |
| 167 | + output_tensor->dims->data[0]), |
| 168 | + TfLiteSupportStatus::kInvalidOutputTensorDimensionsError); |
| 169 | + } |
| 170 | + // TODO: Will the output be float and should be converted or directly available? |
| 171 | + // The example had float and it had to be converted. Anyway, we're guaranteed to have uint8 as output. |
| 172 | + has_uint8_outputs_ = (output_tensor->type == kTfLiteUInt8); |
| 173 | + return absl::OkStatus(); |
| 174 | +} |
| 175 | + |
| 176 | +StatusOr<TransformationResult> ImageTransformer::Transform( |
| 177 | + const FrameBuffer& frame_buffer) { |
| 178 | + BoundingBox roi; |
| 179 | + roi.set_width(frame_buffer.dimension().width); |
| 180 | + roi.set_height(frame_buffer.dimension().height); |
| 181 | + return Transform(frame_buffer, roi); |
| 182 | +} |
| 183 | + |
| 184 | +StatusOr<TransformationResult> ImageTransformer::Transform( |
| 185 | + const FrameBuffer& frame_buffer, const BoundingBox& roi) { |
| 186 | + return InferWithFallback(frame_buffer, roi); |
| 187 | +} |
| 188 | + |
| 189 | +StatusOr<std::unique_ptr<FrameBuffer>> ImageTransformer::Postprocess( |
| 190 | + const std::vector<const TfLiteTensor*>& output_tensors, |
| 191 | + const FrameBuffer& /*frame_buffer*/, const BoundingBox& /*roi*/) { |
| 192 | +} |
| 193 | +} // namespace vision |
| 194 | +} // namespace task |
| 195 | +} // namespace tflite |
0 commit comments