blob: d384032468d5b95dfe32c198613dc9d0b132478b [file] [log] [blame]
Éanna Ó Catháin8f958872021-09-15 09:32:30 +01001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#include "UseCaseHandler.hpp"
18#include "VisualWakeWordModel.hpp"
19#include "Classifier.hpp"
20#include "InputFiles.hpp"
21#include "UseCaseCommonUtils.hpp"
22#include "hal.h"
23
Isabella Gottardi79d41542021-10-20 15:52:32 +010024#include <algorithm>
25
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010026namespace arm {
27namespace app {
28
29 /**
30 * @brief Helper function to load the current image into the input
31 * tensor.
32 * @param[in] imIdx Image index (from the pool of images available
33 * to the application).
34 * @param[out] inputTensor Pointer to the input tensor to be populated.
35 * @return true if tensor is loaded, false otherwise.
36 **/
37 static bool LoadImageIntoTensor(uint32_t imIdx,
38 TfLiteTensor *inputTensor);
39
40 /* Image inference classification handler. */
41 bool ClassifyImageHandler(ApplicationContext &ctx, uint32_t imgIndex, bool runAll)
42 {
43 auto& platform = ctx.Get<hal_platform &>("platform");
44 auto& profiler = ctx.Get<Profiler&>("profiler");
45
46 constexpr uint32_t dataPsnImgDownscaleFactor = 1;
47 constexpr uint32_t dataPsnImgStartX = 10;
48 constexpr uint32_t dataPsnImgStartY = 35;
49
50 constexpr uint32_t dataPsnTxtInfStartX = 150;
51 constexpr uint32_t dataPsnTxtInfStartY = 70;
52
53
54 platform.data_psn->clear(COLOR_BLACK);
55 time_t infTimeMs = 0;
56
57 auto& model = ctx.Get<Model&>("model");
58
59 /* If the request has a valid size, set the image index. */
60 if (imgIndex < NUMBER_OF_FILES) {
61 if (!SetAppCtxIfmIdx(ctx, imgIndex,"imgIndex")) {
62 return false;
63 }
64 }
65 if (!model.IsInited()) {
66 printf_err("Model is not initialised! Terminating processing.\n");
67 return false;
68 }
69
70 auto curImIdx = ctx.Get<uint32_t>("imgIndex");
71
72 TfLiteTensor *outputTensor = model.GetOutputTensor(0);
73 TfLiteTensor *inputTensor = model.GetInputTensor(0);
74
75 if (!inputTensor->dims) {
76 printf_err("Invalid input tensor dims\n");
77 return false;
78 } else if (inputTensor->dims->size < 3) {
79 printf_err("Input tensor dimension should be >= 3\n");
80 return false;
81 }
82 TfLiteIntArray* inputShape = model.GetInputShape(0);
83 const uint32_t nCols = inputShape->data[2];
84 const uint32_t nRows = inputShape->data[1];
85 const uint32_t nChannels = (inputShape->size == 4) ? inputShape->data[3] : 1;
86
87 std::vector<ClassificationResult> results;
88
89 do {
90
91 /* Strings for presentation/logging. */
92 std::string str_inf{"Running inference... "};
93
94 /* Copy over the data. */
95 LoadImageIntoTensor(ctx.Get<uint32_t>("imgIndex"), inputTensor);
96
97 /* Display this image on the LCD. */
98 platform.data_psn->present_data_image(
Isabella Gottardi79d41542021-10-20 15:52:32 +010099 static_cast<uint8_t *>(inputTensor->data.data),
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100100 nCols, nRows, nChannels,
101 dataPsnImgStartX, dataPsnImgStartY, dataPsnImgDownscaleFactor);
102
Isabella Gottardi79d41542021-10-20 15:52:32 +0100103 /* Vww model preprocessing is image conversion from uint8 to [0,1] float values,
104 * then quantize them with input quantization info. */
105 QuantParams inQuantParams = GetTensorQuantParams(inputTensor);
106
107 auto* req_data = static_cast<uint8_t *>(inputTensor->data.data);
108 auto* signed_req_data = static_cast<int8_t *>(inputTensor->data.data);
109 for (size_t i = 0; i < inputTensor->bytes; i++) {
110 auto i_data_int8 = static_cast<int8_t>(((static_cast<float>(req_data[i]) / 255.0f) / inQuantParams.scale) + inQuantParams.offset);
111 signed_req_data[i] = std::min<int8_t>(INT8_MAX, std::max<int8_t>(i_data_int8, INT8_MIN));
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100112 }
113
114 /* Display message on the LCD - inference running. */
115 platform.data_psn->present_data_text(
116 str_inf.c_str(), str_inf.size(),
117 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
118
119 /* Run inference over this image. */
120 info("Running inference on image %" PRIu32 " => %s\n", ctx.Get<uint32_t>("imgIndex"),
121 get_filename(ctx.Get<uint32_t>("imgIndex")));
122
123 if (!RunInference(model, profiler)) {
124 return false;
125 }
126
127 /* Erase. */
128 str_inf = std::string(str_inf.size(), ' ');
129 platform.data_psn->present_data_text(
130 str_inf.c_str(), str_inf.size(),
131 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
132
133 auto& classifier = ctx.Get<Classifier&>("classifier");
134 classifier.GetClassificationResults(outputTensor, results,
135 ctx.Get<std::vector <std::string>&>("labels"), 1);
136
137 /* Add results to context for access outside handler. */
138 ctx.Set<std::vector<ClassificationResult>>("results", results);
139
140#if VERIFY_TEST_OUTPUT
141 arm::app::DumpTensor(outputTensor);
142#endif /* VERIFY_TEST_OUTPUT */
143
144 if (!image::PresentInferenceResult(platform, results, infTimeMs)) {
145 return false;
146 }
147
148 profiler.PrintProfilingResult();
149 IncrementAppCtxIfmIdx(ctx,"imgIndex");
150
151 } while (runAll && ctx.Get<uint32_t>("imgIndex") != curImIdx);
152
153 return true;
154 }
155
156 static bool LoadImageIntoTensor(const uint32_t imIdx,
157 TfLiteTensor *inputTensor)
158 {
159 const size_t copySz = inputTensor->bytes < IMAGE_DATA_SIZE ?
160 inputTensor->bytes : IMAGE_DATA_SIZE;
161 if (imIdx >= NUMBER_OF_FILES) {
162 printf_err("invalid image index %" PRIu32 " (max: %u)\n", imIdx,
163 NUMBER_OF_FILES - 1);
164 return false;
165 }
166
167 const uint32_t nChannels = (inputTensor->dims->size == 4) ? inputTensor->dims->data[3] : 1;
168
169 const uint8_t* srcPtr = get_img_array(imIdx);
Isabella Gottardi79d41542021-10-20 15:52:32 +0100170 auto* dstPtr = static_cast<uint8_t *>(inputTensor->data.data);
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100171 if (1 == nChannels) {
172 /**
173 * Visual Wake Word model accepts only one channel =>
174 * Convert image to grayscale here
175 **/
176 for (size_t i = 0; i < copySz; ++i, srcPtr += 3) {
177 *dstPtr++ = 0.2989*(*srcPtr) +
178 0.587*(*(srcPtr+1)) +
179 0.114*(*(srcPtr+2));
180 }
181 } else {
182 memcpy(inputTensor->data.data, srcPtr, copySz);
183 }
184
185 debug("Image %" PRIu32 " loaded\n", imIdx);
186 return true;
187 }
188
189} /* namespace app */
190} /* namespace arm */