blob: dccf5ffdcd4fc78d0f97966b1d2d89793d71cd76 [file] [log] [blame]
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
SiCong Li39f46392019-06-21 12:00:04 +01006#include "../ImageTensorGenerator/ImageTensorGenerator.hpp"
7#include "../InferenceTest.hpp"
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01008#include "ModelAccuracyChecker.hpp"
Éanna Ó Catháina4247d52019-05-08 14:00:45 +01009#include "armnnDeserializer/IDeserializer.hpp"
Francis Murtagh532a29d2020-06-29 11:50:01 +010010#include <Filesystem.hpp>
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010011
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010012#include <boost/program_options/variables_map.hpp>
SiCong Li39f46392019-06-21 12:00:04 +010013#include <map>
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010014
15using namespace armnn::test;
16
SiCong Li898a3242019-06-24 16:03:33 +010017/** Load image names and ground-truth labels from the image directory and the ground truth label file
18 *
19 * @pre \p validationLabelPath exists and is valid regular file
20 * @pre \p imageDirectoryPath exists and is valid directory
21 * @pre labels in validation file correspond to images which are in lexicographical order with the image name
22 * @pre image index starts at 1
23 * @pre \p begIndex and \p endIndex are end-inclusive
24 *
25 * @param[in] validationLabelPath Path to validation label file
26 * @param[in] imageDirectoryPath Path to directory containing validation images
27 * @param[in] begIndex Begin index of images to be loaded. Inclusive
28 * @param[in] endIndex End index of images to be loaded. Inclusive
29 * @param[in] blacklistPath Path to blacklist file
30 * @return A map mapping image file names to their corresponding ground-truth labels
31 */
32map<std::string, std::string> LoadValidationImageFilenamesAndLabels(const string& validationLabelPath,
33 const string& imageDirectoryPath,
34 size_t begIndex = 0,
35 size_t endIndex = 0,
36 const string& blacklistPath = "");
37
38/** Load model output labels from file
39 *
40 * @pre \p modelOutputLabelsPath exists and is a regular file
41 *
42 * @param[in] modelOutputLabelsPath path to model output labels file
43 * @return A vector of labels, which in turn is described by a list of category names
44 */
45std::vector<armnnUtils::LabelCategoryNames> LoadModelOutputLabels(const std::string& modelOutputLabelsPath);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010046
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010047int main(int argc, char* argv[])
48{
49 try
50 {
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010051 armnn::LogSeverity level = armnn::LogSeverity::Debug;
52 armnn::ConfigureLogging(true, true, level);
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010053
54 // Set-up program Options
55 namespace po = boost::program_options;
56
57 std::vector<armnn::BackendId> computeDevice;
58 std::vector<armnn::BackendId> defaultBackends = {armnn::Compute::CpuAcc, armnn::Compute::CpuRef};
59 std::string modelPath;
SiCong Li39f46392019-06-21 12:00:04 +010060 std::string modelFormat;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010061 std::string dataDir;
62 std::string inputName;
SiCong Li39f46392019-06-21 12:00:04 +010063 std::string inputLayout;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010064 std::string outputName;
SiCong Li898a3242019-06-24 16:03:33 +010065 std::string modelOutputLabelsPath;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010066 std::string validationLabelPath;
SiCong Li898a3242019-06-24 16:03:33 +010067 std::string validationRange;
68 std::string blacklistPath;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010069
70 const std::string backendsMessage = "Which device to run layers on by default. Possible choices: "
71 + armnn::BackendRegistryInstance().GetBackendIdsAsString();
72
73 po::options_description desc("Options");
74 try
75 {
76 // Adds generic options needed to run Accuracy Tool.
77 desc.add_options()
Conor Kennedy30562022019-05-13 14:48:58 +010078 ("help,h", "Display help messages")
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010079 ("model-path,m", po::value<std::string>(&modelPath)->required(), "Path to armnn format model file")
SiCong Li39f46392019-06-21 12:00:04 +010080 ("model-format,f", po::value<std::string>(&modelFormat)->required(),
81 "The model format. Supported values: caffe, tensorflow, tflite")
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010082 ("input-name,i", po::value<std::string>(&inputName)->required(),
83 "Identifier of the input tensors in the network separated by comma.")
84 ("output-name,o", po::value<std::string>(&outputName)->required(),
85 "Identifier of the output tensors in the network separated by comma.")
SiCong Li39f46392019-06-21 12:00:04 +010086 ("data-dir,d", po::value<std::string>(&dataDir)->required(),
87 "Path to directory containing the ImageNet test data")
SiCong Li898a3242019-06-24 16:03:33 +010088 ("model-output-labels,p", po::value<std::string>(&modelOutputLabelsPath)->required(),
89 "Path to model output labels file.")
Éanna Ó Catháina4247d52019-05-08 14:00:45 +010090 ("validation-labels-path,v", po::value<std::string>(&validationLabelPath)->required(),
SiCong Li39f46392019-06-21 12:00:04 +010091 "Path to ImageNet Validation Label file")
92 ("data-layout,l", po::value<std::string>(&inputLayout)->default_value("NHWC"),
SiCong Li23700bb2019-07-25 14:54:39 +010093 "Data layout. Supported value: NHWC, NCHW. Default: NHWC")
SiCong Li39f46392019-06-21 12:00:04 +010094 ("compute,c", po::value<std::vector<armnn::BackendId>>(&computeDevice)->default_value(defaultBackends),
SiCong Li898a3242019-06-24 16:03:33 +010095 backendsMessage.c_str())
96 ("validation-range,r", po::value<std::string>(&validationRange)->default_value("1:0"),
97 "The range of the images to be evaluated. Specified in the form <begin index>:<end index>."
98 "The index starts at 1 and the range is inclusive."
99 "By default the evaluation will be performed on all images.")
100 ("blacklist-path,b", po::value<std::string>(&blacklistPath)->default_value(""),
101 "Path to a blacklist file where each line denotes the index of an image to be "
102 "excluded from evaluation.");
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100103 }
104 catch (const std::exception& e)
105 {
106 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
107 // and that desc.add_options() can throw boost::io::too_few_args.
108 // They really won't in any of these cases.
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100109 ARMNN_ASSERT_MSG(false, "Caught unexpected exception");
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100110 std::cerr << "Fatal internal error: " << e.what() << std::endl;
111 return 1;
112 }
113
114 po::variables_map vm;
115 try
116 {
117 po::store(po::parse_command_line(argc, argv, desc), vm);
118
119 if (vm.count("help"))
120 {
121 std::cout << desc << std::endl;
122 return 1;
123 }
124 po::notify(vm);
125 }
126 catch (po::error& e)
127 {
128 std::cerr << e.what() << std::endl << std::endl;
129 std::cerr << desc << std::endl;
130 return 1;
131 }
132
133 // Check if the requested backend are all valid
134 std::string invalidBackends;
135 if (!CheckRequestedBackendsAreValid(computeDevice, armnn::Optional<std::string&>(invalidBackends)))
136 {
Derek Lamberti08446972019-11-26 16:38:31 +0000137 ARMNN_LOG(fatal) << "The list of preferred devices contains invalid backend IDs: "
138 << invalidBackends;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100139 return EXIT_FAILURE;
140 }
141 armnn::Status status;
142
143 // Create runtime
144 armnn::IRuntime::CreationOptions options;
145 armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options));
146 std::ifstream file(modelPath);
147
148 // Create Parser
149 using IParser = armnnDeserializer::IDeserializer;
150 auto armnnparser(IParser::Create());
151
152 // Create a network
153 armnn::INetworkPtr network = armnnparser->CreateNetworkFromBinary(file);
154
155 // Optimizes the network.
156 armnn::IOptimizedNetworkPtr optimizedNet(nullptr, nullptr);
157 try
158 {
159 optimizedNet = armnn::Optimize(*network, computeDevice, runtime->GetDeviceSpec());
160 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000161 catch (const armnn::Exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100162 {
163 std::stringstream message;
164 message << "armnn::Exception (" << e.what() << ") caught from optimize.";
Derek Lamberti08446972019-11-26 16:38:31 +0000165 ARMNN_LOG(fatal) << message.str();
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100166 return 1;
167 }
168
169 // Loads the network into the runtime.
170 armnn::NetworkId networkId;
171 status = runtime->LoadNetwork(networkId, std::move(optimizedNet));
172 if (status == armnn::Status::Failure)
173 {
Derek Lamberti08446972019-11-26 16:38:31 +0000174 ARMNN_LOG(fatal) << "armnn::IRuntime: Failed to load network";
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100175 return 1;
176 }
177
178 // Set up Network
179 using BindingPointInfo = InferenceModelInternal::BindingPointInfo;
180
181 const armnnDeserializer::BindingPointInfo&
182 inputBindingInfo = armnnparser->GetNetworkInputBindingInfo(0, inputName);
183
184 std::pair<armnn::LayerBindingId, armnn::TensorInfo>
185 m_InputBindingInfo(inputBindingInfo.m_BindingId, inputBindingInfo.m_TensorInfo);
186 std::vector<BindingPointInfo> inputBindings = { m_InputBindingInfo };
187
188 const armnnDeserializer::BindingPointInfo&
189 outputBindingInfo = armnnparser->GetNetworkOutputBindingInfo(0, outputName);
190
191 std::pair<armnn::LayerBindingId, armnn::TensorInfo>
192 m_OutputBindingInfo(outputBindingInfo.m_BindingId, outputBindingInfo.m_TensorInfo);
193 std::vector<BindingPointInfo> outputBindings = { m_OutputBindingInfo };
194
SiCong Li898a3242019-06-24 16:03:33 +0100195 // Load model output labels
Francis Murtagh532a29d2020-06-29 11:50:01 +0100196 if (modelOutputLabelsPath.empty() || !fs::exists(modelOutputLabelsPath) ||
197 !fs::is_regular_file(modelOutputLabelsPath))
SiCong Li898a3242019-06-24 16:03:33 +0100198 {
Derek Lamberti08446972019-11-26 16:38:31 +0000199 ARMNN_LOG(fatal) << "Invalid model output labels path at " << modelOutputLabelsPath;
SiCong Li898a3242019-06-24 16:03:33 +0100200 }
201 const std::vector<armnnUtils::LabelCategoryNames> modelOutputLabels =
202 LoadModelOutputLabels(modelOutputLabelsPath);
203
204 // Parse begin and end image indices
205 std::vector<std::string> imageIndexStrs = armnnUtils::SplitBy(validationRange, ":");
206 size_t imageBegIndex;
207 size_t imageEndIndex;
208 if (imageIndexStrs.size() != 2)
209 {
Derek Lamberti08446972019-11-26 16:38:31 +0000210 ARMNN_LOG(fatal) << "Invalid validation range specification: Invalid format " << validationRange;
SiCong Li898a3242019-06-24 16:03:33 +0100211 return 1;
212 }
213 try
214 {
215 imageBegIndex = std::stoul(imageIndexStrs[0]);
216 imageEndIndex = std::stoul(imageIndexStrs[1]);
217 }
218 catch (const std::exception& e)
219 {
Derek Lamberti08446972019-11-26 16:38:31 +0000220 ARMNN_LOG(fatal) << "Invalid validation range specification: " << validationRange;
SiCong Li898a3242019-06-24 16:03:33 +0100221 return 1;
222 }
223
224 // Validate blacklist file if it's specified
225 if (!blacklistPath.empty() &&
Francis Murtagh532a29d2020-06-29 11:50:01 +0100226 !(fs::exists(blacklistPath) && fs::is_regular_file(blacklistPath)))
SiCong Li898a3242019-06-24 16:03:33 +0100227 {
Derek Lamberti08446972019-11-26 16:38:31 +0000228 ARMNN_LOG(fatal) << "Invalid path to blacklist file at " << blacklistPath;
SiCong Li898a3242019-06-24 16:03:33 +0100229 return 1;
230 }
231
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100232 path pathToDataDir(dataDir);
SiCong Li898a3242019-06-24 16:03:33 +0100233 const map<std::string, std::string> imageNameToLabel = LoadValidationImageFilenamesAndLabels(
234 validationLabelPath, pathToDataDir.string(), imageBegIndex, imageEndIndex, blacklistPath);
235 armnnUtils::ModelAccuracyChecker checker(imageNameToLabel, modelOutputLabels);
James Ward6d9f5c52020-09-28 11:56:35 +0100236 using TContainer = mapbox::util::variant<std::vector<float>, std::vector<int>, std::vector<uint8_t>>;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100237
SiCong Li39f46392019-06-21 12:00:04 +0100238 if (ValidateDirectory(dataDir))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100239 {
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100240 InferenceModel<armnnDeserializer::IDeserializer, float>::Params params;
SiCong Li39f46392019-06-21 12:00:04 +0100241 params.m_ModelPath = modelPath;
242 params.m_IsModelBinary = true;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100243 params.m_ComputeDevices = computeDevice;
244 params.m_InputBindings.push_back(inputName);
245 params.m_OutputBindings.push_back(outputName);
246
247 using TParser = armnnDeserializer::IDeserializer;
248 InferenceModel<TParser, float> model(params, false);
SiCong Li39f46392019-06-21 12:00:04 +0100249 // Get input tensor information
250 const armnn::TensorInfo& inputTensorInfo = model.GetInputBindingInfo().second;
251 const armnn::TensorShape& inputTensorShape = inputTensorInfo.GetShape();
252 const armnn::DataType& inputTensorDataType = inputTensorInfo.GetDataType();
253 armnn::DataLayout inputTensorDataLayout;
254 if (inputLayout == "NCHW")
255 {
256 inputTensorDataLayout = armnn::DataLayout::NCHW;
257 }
258 else if (inputLayout == "NHWC")
259 {
260 inputTensorDataLayout = armnn::DataLayout::NHWC;
261 }
262 else
263 {
Derek Lamberti08446972019-11-26 16:38:31 +0000264 ARMNN_LOG(fatal) << "Invalid Data layout: " << inputLayout;
SiCong Li39f46392019-06-21 12:00:04 +0100265 return 1;
266 }
267 const unsigned int inputTensorWidth =
268 inputTensorDataLayout == armnn::DataLayout::NCHW ? inputTensorShape[3] : inputTensorShape[2];
269 const unsigned int inputTensorHeight =
270 inputTensorDataLayout == armnn::DataLayout::NCHW ? inputTensorShape[2] : inputTensorShape[1];
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100271 // Get output tensor info
272 const unsigned int outputNumElements = model.GetOutputSize();
SiCong Li898a3242019-06-24 16:03:33 +0100273 // Check output tensor shape is valid
274 if (modelOutputLabels.size() != outputNumElements)
275 {
Derek Lamberti08446972019-11-26 16:38:31 +0000276 ARMNN_LOG(fatal) << "Number of output elements: " << outputNumElements
SiCong Li898a3242019-06-24 16:03:33 +0100277 << " , mismatches the number of output labels: " << modelOutputLabels.size();
278 return 1;
279 }
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100280
SiCong Li39f46392019-06-21 12:00:04 +0100281 const unsigned int batchSize = 1;
282 // Get normalisation parameters
283 SupportedFrontend modelFrontend;
284 if (modelFormat == "caffe")
285 {
286 modelFrontend = SupportedFrontend::Caffe;
287 }
288 else if (modelFormat == "tensorflow")
289 {
290 modelFrontend = SupportedFrontend::TensorFlow;
291 }
292 else if (modelFormat == "tflite")
293 {
294 modelFrontend = SupportedFrontend::TFLite;
295 }
296 else
297 {
Derek Lamberti08446972019-11-26 16:38:31 +0000298 ARMNN_LOG(fatal) << "Unsupported frontend: " << modelFormat;
SiCong Li39f46392019-06-21 12:00:04 +0100299 return 1;
300 }
301 const NormalizationParameters& normParams = GetNormalizationParameters(modelFrontend, inputTensorDataType);
SiCong Li898a3242019-06-24 16:03:33 +0100302 for (const auto& imageEntry : imageNameToLabel)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100303 {
SiCong Li898a3242019-06-24 16:03:33 +0100304 const std::string imageName = imageEntry.first;
305 std::cout << "Processing image: " << imageName << "\n";
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100306
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100307 vector<TContainer> inputDataContainers;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100308 vector<TContainer> outputDataContainers;
309
Francis Murtagh532a29d2020-06-29 11:50:01 +0100310 auto imagePath = pathToDataDir / fs::path(imageName);
SiCong Li39f46392019-06-21 12:00:04 +0100311 switch (inputTensorDataType)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100312 {
SiCong Li39f46392019-06-21 12:00:04 +0100313 case armnn::DataType::Signed32:
314 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100315 PrepareImageTensor<int>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100316 inputTensorWidth, inputTensorHeight,
317 normParams,
318 batchSize,
319 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100320 outputDataContainers = { vector<int>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100321 break;
Derek Lambertif90c56d2020-01-10 17:14:08 +0000322 case armnn::DataType::QAsymmU8:
SiCong Li39f46392019-06-21 12:00:04 +0100323 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100324 PrepareImageTensor<uint8_t>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100325 inputTensorWidth, inputTensorHeight,
326 normParams,
327 batchSize,
328 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100329 outputDataContainers = { vector<uint8_t>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100330 break;
331 case armnn::DataType::Float32:
332 default:
333 inputDataContainers.push_back(
SiCong Li898a3242019-06-24 16:03:33 +0100334 PrepareImageTensor<float>(imagePath.string(),
SiCong Li39f46392019-06-21 12:00:04 +0100335 inputTensorWidth, inputTensorHeight,
336 normParams,
337 batchSize,
338 inputTensorDataLayout));
SiCong Lic0ed7ba2019-06-21 16:02:40 +0100339 outputDataContainers = { vector<float>(outputNumElements) };
SiCong Li39f46392019-06-21 12:00:04 +0100340 break;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100341 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100342
343 status = runtime->EnqueueWorkload(networkId,
344 armnnUtils::MakeInputTensors(inputBindings, inputDataContainers),
345 armnnUtils::MakeOutputTensors(outputBindings, outputDataContainers));
346
347 if (status == armnn::Status::Failure)
348 {
Derek Lamberti08446972019-11-26 16:38:31 +0000349 ARMNN_LOG(fatal) << "armnn::IRuntime: Failed to enqueue workload for image: " << imageName;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100350 }
351
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100352 checker.AddImageResult<TContainer>(imageName, outputDataContainers);
353 }
354 }
355 else
356 {
357 return 1;
358 }
359
360 for(unsigned int i = 1; i <= 5; ++i)
361 {
362 std::cout << "Top " << i << " Accuracy: " << checker.GetAccuracy(i) << "%" << "\n";
363 }
364
Derek Lamberti08446972019-11-26 16:38:31 +0000365 ARMNN_LOG(info) << "Accuracy Tool ran successfully!";
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100366 return 0;
367 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000368 catch (const armnn::Exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100369 {
370 // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
371 // exception of type std::length_error.
372 // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
373 std::cerr << "Armnn Error: " << e.what() << std::endl;
374 return 1;
375 }
Pavel Macenauer855a47b2020-05-26 10:54:22 +0000376 catch (const std::exception& e)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100377 {
378 // Coverity fix: various boost exceptions can be thrown by methods called by this test.
379 std::cerr << "WARNING: ModelAccuracyTool-Armnn: An error has occurred when running the "
380 "Accuracy Tool: " << e.what() << std::endl;
381 return 1;
382 }
383}
384
SiCong Li898a3242019-06-24 16:03:33 +0100385map<std::string, std::string> LoadValidationImageFilenamesAndLabels(const string& validationLabelPath,
386 const string& imageDirectoryPath,
387 size_t begIndex,
388 size_t endIndex,
389 const string& blacklistPath)
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100390{
SiCong Li898a3242019-06-24 16:03:33 +0100391 // Populate imageFilenames with names of all .JPEG, .PNG images
392 std::vector<std::string> imageFilenames;
Matthew Sloyan2b428032020-10-06 10:45:32 +0100393 for (const auto& imageEntry : fs::directory_iterator(fs::path(imageDirectoryPath)))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100394 {
Francis Murtagh532a29d2020-06-29 11:50:01 +0100395 fs::path imagePath = imageEntry.path();
Matthew Sloyan2b428032020-10-06 10:45:32 +0100396
397 // Get extension and convert to uppercase
398 std::string imageExtension = imagePath.extension().string();
399 std::transform(imageExtension.begin(), imageExtension.end(), imageExtension.begin(), ::toupper);
400
Francis Murtagh532a29d2020-06-29 11:50:01 +0100401 if (fs::is_regular_file(imagePath) && (imageExtension == ".JPEG" || imageExtension == ".PNG"))
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100402 {
SiCong Li898a3242019-06-24 16:03:33 +0100403 imageFilenames.push_back(imagePath.filename().string());
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100404 }
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100405 }
SiCong Li898a3242019-06-24 16:03:33 +0100406 if (imageFilenames.empty())
407 {
408 throw armnn::Exception("No image file (JPEG, PNG) found at " + imageDirectoryPath);
409 }
410
411 // Sort the image filenames lexicographically
412 std::sort(imageFilenames.begin(), imageFilenames.end());
413
414 std::cout << imageFilenames.size() << " images found at " << imageDirectoryPath << std::endl;
415
416 // Get default end index
417 if (begIndex < 1 || endIndex > imageFilenames.size())
418 {
419 throw armnn::Exception("Invalid image index range");
420 }
421 endIndex = endIndex == 0 ? imageFilenames.size() : endIndex;
422 if (begIndex > endIndex)
423 {
424 throw armnn::Exception("Invalid image index range");
425 }
426
427 // Load blacklist if there is one
428 std::vector<unsigned int> blacklist;
429 if (!blacklistPath.empty())
430 {
431 std::ifstream blacklistFile(blacklistPath);
432 unsigned int index;
433 while (blacklistFile >> index)
434 {
435 blacklist.push_back(index);
436 }
437 }
438
439 // Load ground truth labels and pair them with corresponding image names
440 std::string classification;
441 map<std::string, std::string> imageNameToLabel;
442 ifstream infile(validationLabelPath);
443 size_t imageIndex = begIndex;
444 size_t blacklistIndexCount = 0;
445 while (std::getline(infile, classification))
446 {
447 if (imageIndex > endIndex)
448 {
449 break;
450 }
451 // If current imageIndex is included in blacklist, skip the current image
452 if (blacklistIndexCount < blacklist.size() && imageIndex == blacklist[blacklistIndexCount])
453 {
454 ++imageIndex;
455 ++blacklistIndexCount;
456 continue;
457 }
458 imageNameToLabel.insert(std::pair<std::string, std::string>(imageFilenames[imageIndex - 1], classification));
459 ++imageIndex;
460 }
461 std::cout << blacklistIndexCount << " images blacklisted" << std::endl;
462 std::cout << imageIndex - begIndex - blacklistIndexCount << " images to be loaded" << std::endl;
463 return imageNameToLabel;
Éanna Ó Catháina4247d52019-05-08 14:00:45 +0100464}
SiCong Li898a3242019-06-24 16:03:33 +0100465
466std::vector<armnnUtils::LabelCategoryNames> LoadModelOutputLabels(const std::string& modelOutputLabelsPath)
467{
468 std::vector<armnnUtils::LabelCategoryNames> modelOutputLabels;
469 ifstream modelOutputLablesFile(modelOutputLabelsPath);
470 std::string line;
471 while (std::getline(modelOutputLablesFile, line))
472 {
473 armnnUtils::LabelCategoryNames tokens = armnnUtils::SplitBy(line, ":");
474 armnnUtils::LabelCategoryNames predictionCategoryNames = armnnUtils::SplitBy(tokens.back(), ",");
475 std::transform(predictionCategoryNames.begin(), predictionCategoryNames.end(), predictionCategoryNames.begin(),
476 [](const std::string& category) { return armnnUtils::Strip(category); });
477 modelOutputLabels.push_back(predictionCategoryNames);
478 }
479 return modelOutputLabels;
480}