blob: 0c85136a3854790ff7a229afee192c8cfeb65db5 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 2017 ARM Limited.
3 *
4 * SPDX-License-Identifier: MIT
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24#include "TensorLibrary.h"
25
26#include "TypePrinter.h"
27#include "UserConfiguration.h"
28#include "Utils.h"
29
30#include "arm_compute/core/ITensor.h"
31
32#include <cctype>
33#include <fstream>
34#include <limits>
35#include <map>
36#include <mutex>
37#include <sstream>
38#include <stdexcept>
39#include <tuple>
40#include <unordered_map>
41#include <utility>
42
43namespace arm_compute
44{
45namespace test
46{
47namespace
48{
49void convert_rgb_to_u8(const RawTensor &src, RawTensor &dst)
50{
51 const size_t min_size = std::min(src.size(), dst.size());
52
53 for(size_t i = 0, j = 0; i < min_size; i += 3, ++j)
54 {
55 dst.data()[j] = 0.2126f * src.data()[i + 0] + 0.7152f * src.data()[i + 1] + 0.0722f * src.data()[i + 2];
56 }
57}
58
59void convert_rgb_to_u16(const RawTensor &src, RawTensor &dst)
60{
61 const size_t min_size = std::min(src.size(), dst.size());
62
63 for(size_t i = 0, j = 0; i < min_size; i += 3, ++j)
64 {
65 reinterpret_cast<uint16_t *>(dst.data())[j] = 0.2126f * src.data()[i + 0] + 0.7152f * src.data()[i + 1] + 0.0722f * src.data()[i + 2];
66 }
67}
68
69void convert_rgb_to_s16(const RawTensor &src, RawTensor &dst)
70{
71 const size_t min_size = std::min(src.size(), dst.size());
72
73 for(size_t i = 0, j = 0; i < min_size; i += 3, ++j)
74 {
75 reinterpret_cast<int16_t *>(dst.data())[j] = 0.2126f * src.data()[i + 0] + 0.7152f * src.data()[i + 1] + 0.0722f * src.data()[i + 2];
76 }
77}
78
79void extract_r_from_rgb(const RawTensor &src, RawTensor &dst)
80{
81 const size_t min_size = std::min(src.size(), dst.size());
82
83 for(size_t i = 0, j = 0; i < min_size; i += 3, ++j)
84 {
85 dst.data()[j] = src.data()[i];
86 }
87}
88
89void extract_g_from_rgb(const RawTensor &src, RawTensor &dst)
90{
91 const size_t min_size = std::min(src.size(), dst.size());
92
93 for(size_t i = 1, j = 0; i < min_size; i += 3, ++j)
94 {
95 dst.data()[j] = src.data()[i];
96 }
97}
98
99void discard_comments(std::ifstream &fs)
100{
101 while(fs.peek() == '#')
102 {
103 fs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
104 }
105}
106
107void discard_comments_and_spaces(std::ifstream &fs)
108{
109 while(true)
110 {
111 discard_comments(fs);
112
113 if(isspace(fs.peek()) == 0)
114 {
115 break;
116 }
117
118 fs.ignore(1);
119 }
120}
121
122std::tuple<unsigned int, unsigned int, int> parse_ppm_header(std::ifstream &fs)
123{
124 // Check the PPM magic number is valid
125 std::array<char, 2> magic_number{ { 0 } };
126 fs >> magic_number[0] >> magic_number[1];
127
128 if(magic_number[0] != 'P' || magic_number[1] != '6')
129 {
130 throw std::runtime_error("Only raw PPM format is suported");
131 }
132
133 discard_comments_and_spaces(fs);
134
135 unsigned int width = 0;
136 fs >> width;
137
138 discard_comments_and_spaces(fs);
139
140 unsigned int height = 0;
141 fs >> height;
142
143 discard_comments_and_spaces(fs);
144
145 int max_value = 0;
146 fs >> max_value;
147
148 if(!fs.good())
149 {
150 throw std::runtime_error("Cannot read image dimensions");
151 }
152
153 if(max_value != 255)
154 {
155 throw std::runtime_error("RawTensor doesn't have 8-bit values");
156 }
157
158 discard_comments(fs);
159
160 if(isspace(fs.peek()) == 0)
161 {
162 throw std::runtime_error("Invalid PPM header");
163 }
164
165 fs.ignore(1);
166
167 return std::make_tuple(width, height, max_value);
168}
169
170RawTensor load_ppm(const std::string &path)
171{
172 std::ifstream file(path, std::ios::in | std::ios::binary);
173
174 if(!file.good())
175 {
176 throw std::runtime_error("Could not load PPM image: " + path);
177 }
178
179 unsigned int width = 0;
180 unsigned int height = 0;
181
182 std::tie(width, height, std::ignore) = parse_ppm_header(file);
183
184 RawTensor raw(TensorShape(width, height), Format::RGB888);
185
186 // Check if the file is large enough to fill the image
187 const size_t current_position = file.tellg();
188 file.seekg(0, std::ios_base::end);
189 const size_t end_position = file.tellg();
190 file.seekg(current_position, std::ios_base::beg);
191
192 if((end_position - current_position) < raw.size())
193 {
194 throw std::runtime_error("Not enough data in file");
195 }
196
197 file.read(reinterpret_cast<std::fstream::char_type *>(raw.data()), raw.size());
198
199 if(!file.good())
200 {
201 throw std::runtime_error("Failure while reading image buffer");
202 }
203
204 return raw;
205}
206} // namespace
207
208TensorLibrary::TensorLibrary(std::string path)
209 : _library_path(std::move(path)), _seed{ std::random_device()() }
210{
211}
212
213TensorLibrary::TensorLibrary(std::string path, std::random_device::result_type seed)
214 : _library_path(std::move(path)), _seed{ seed }
215{
216}
217
218std::random_device::result_type TensorLibrary::seed() const
219{
220 return _seed;
221}
222
223void TensorLibrary::fill(RawTensor &raw, const std::string &name, Format format) const
224{
225 //FIXME: Should be done by swapping cached buffers
226 const RawTensor &src = get(name, format);
227 std::copy_n(src.data(), raw.size(), raw.data());
228}
229
230void TensorLibrary::fill(RawTensor &raw, const std::string &name, Channel channel) const
231{
232 fill(raw, name, get_format_for_channel(channel), channel);
233}
234
235void TensorLibrary::fill(RawTensor &raw, const std::string &name, Format format, Channel channel) const
236{
237 const RawTensor &src = get(name, format, channel);
238 std::copy_n(src.data(), raw.size(), raw.data());
239}
240
241const TensorLibrary::Loader &TensorLibrary::get_loader(const std::string &extension) const
242{
243 static std::unordered_map<std::string, Loader> loaders =
244 {
245 { "ppm", load_ppm }
246 };
247
248 const auto it = loaders.find(extension);
249
250 if(it != loaders.end())
251 {
252 return it->second;
253 }
254 else
255 {
256 throw std::invalid_argument("Cannot load image with extension '" + extension + "'");
257 }
258}
259
260const TensorLibrary::Converter &TensorLibrary::get_converter(Format src, Format dst) const
261{
262 static std::map<std::pair<Format, Format>, Converter> converters =
263 {
264 { std::make_pair(Format::RGB888, Format::U8), convert_rgb_to_u8 },
265 { std::make_pair(Format::RGB888, Format::U16), convert_rgb_to_u16 },
266 { std::make_pair(Format::RGB888, Format::S16), convert_rgb_to_s16 }
267 };
268
269 const auto it = converters.find(std::make_pair(src, dst));
270
271 if(it != converters.end())
272 {
273 return it->second;
274 }
275 else
276 {
277 std::stringstream msg;
278 msg << "Cannot convert from format '" << src << "' to format '" << dst << "'\n";
279 throw std::invalid_argument(msg.str());
280 }
281}
282
283const TensorLibrary::Converter &TensorLibrary::get_converter(DataType src, Format dst) const
284{
285 static std::map<std::pair<DataType, Format>, Converter> converters = {};
286
287 const auto it = converters.find(std::make_pair(src, dst));
288
289 if(it != converters.end())
290 {
291 return it->second;
292 }
293 else
294 {
295 std::stringstream msg;
296 msg << "Cannot convert from data type '" << src << "' to format '" << dst << "'\n";
297 throw std::invalid_argument(msg.str());
298 }
299}
300
301const TensorLibrary::Converter &TensorLibrary::get_converter(DataType src, DataType dst) const
302{
303 static std::map<std::pair<DataType, DataType>, Converter> converters = {};
304
305 const auto it = converters.find(std::make_pair(src, dst));
306
307 if(it != converters.end())
308 {
309 return it->second;
310 }
311 else
312 {
313 std::stringstream msg;
314 msg << "Cannot convert from data type '" << src << "' to data type '" << dst << "'\n";
315 throw std::invalid_argument(msg.str());
316 }
317}
318
319const TensorLibrary::Converter &TensorLibrary::get_converter(Format src, DataType dst) const
320{
321 static std::map<std::pair<Format, DataType>, Converter> converters = {};
322
323 const auto it = converters.find(std::make_pair(src, dst));
324
325 if(it != converters.end())
326 {
327 return it->second;
328 }
329 else
330 {
331 std::stringstream msg;
332 msg << "Cannot convert from format '" << src << "' to data type '" << dst << "'\n";
333 throw std::invalid_argument(msg.str());
334 }
335}
336
337const TensorLibrary::Extractor &TensorLibrary::get_extractor(Format format, Channel channel) const
338{
339 static std::map<std::pair<Format, Channel>, Extractor> extractors =
340 {
341 { std::make_pair(Format::RGB888, Channel::R), extract_r_from_rgb },
342 { std::make_pair(Format::RGB888, Channel::G), extract_g_from_rgb }
343 };
344
345 const auto it = extractors.find(std::make_pair(format, channel));
346
347 if(it != extractors.end())
348 {
349 return it->second;
350 }
351 else
352 {
353 std::stringstream msg;
354 msg << "Cannot extract channel '" << channel << "' from format '" << format << "'\n";
355 throw std::invalid_argument(msg.str());
356 }
357}
358
359RawTensor TensorLibrary::load_image(const std::string &name) const
360{
361#ifdef _WIN32
362 const std::string image_path = ("\\images\\");
363#else
364 const std::string image_path = ("/images/");
365#endif
366
367 const std::string path = _library_path + image_path + name;
368 const std::string extension = path.substr(path.find_last_of('.') + 1);
369 return (*get_loader(extension))(path);
370}
371
372const RawTensor &TensorLibrary::find_or_create_raw_tensor(const std::string &name, Format format) const
373{
374 std::lock_guard<std::mutex> guard(_format_lock);
375
376 const RawTensor *ptr = _cache.find(std::make_tuple(name, format));
377
378 if(ptr != nullptr)
379 {
380 return *ptr;
381 }
382
383 RawTensor raw = load_image(name);
384
385 if(raw.format() != format)
386 {
387 //FIXME: Remove unnecessary copy
388 RawTensor dst(raw.shape(), format);
389 (*get_converter(raw.format(), format))(raw, dst);
390 raw = std::move(dst);
391 }
392
393 return _cache.add(std::make_tuple(name, format), std::move(raw));
394}
395
396const RawTensor &TensorLibrary::find_or_create_raw_tensor(const std::string &name, Format format, Channel channel) const
397{
398 std::lock_guard<std::mutex> guard(_channel_lock);
399
400 const RawTensor *ptr = _cache.find(std::make_tuple(name, format, channel));
401
402 if(ptr != nullptr)
403 {
404 return *ptr;
405 }
406
407 const RawTensor &src = get(name, format);
408 //FIXME: Need to change shape to match channel
409 RawTensor dst(src.shape(), get_channel_format(channel));
410
411 (*get_extractor(format, channel))(src, dst);
412
413 return _cache.add(std::make_tuple(name, format, channel), std::move(dst));
414}
415
416RawTensor TensorLibrary::get(const TensorShape &shape, DataType data_type, int num_channels, int fixed_point_position)
417{
418 return RawTensor(shape, data_type, num_channels, fixed_point_position);
419}
420
421RawTensor TensorLibrary::get(const TensorShape &shape, Format format)
422{
423 return RawTensor(shape, format);
424}
425
426const RawTensor &TensorLibrary::get(const std::string &name) const
427{
428 //FIXME: Format should be derived from the image name. Not be fixed to RGB.
429 return find_or_create_raw_tensor(name, Format::RGB888);
430}
431
432RawTensor TensorLibrary::get(const std::string &name)
433{
434 //FIXME: Format should be derived from the image name. Not be fixed to RGB.
435 return RawTensor(find_or_create_raw_tensor(name, Format::RGB888));
436}
437
438RawTensor TensorLibrary::get(const std::string &name, DataType data_type, int num_channels) const
439{
440 const RawTensor &raw = get(name);
441
442 return RawTensor(raw.shape(), data_type, num_channels);
443}
444
445const RawTensor &TensorLibrary::get(const std::string &name, Format format) const
446{
447 return find_or_create_raw_tensor(name, format);
448}
449
450RawTensor TensorLibrary::get(const std::string &name, Format format)
451{
452 return RawTensor(find_or_create_raw_tensor(name, format));
453}
454
455const RawTensor &TensorLibrary::get(const std::string &name, Channel channel) const
456{
457 return get(name, get_format_for_channel(channel), channel);
458}
459
460RawTensor TensorLibrary::get(const std::string &name, Channel channel)
461{
462 return RawTensor(get(name, get_format_for_channel(channel), channel));
463}
464
465const RawTensor &TensorLibrary::get(const std::string &name, Format format, Channel channel) const
466{
467 return find_or_create_raw_tensor(name, format, channel);
468}
469
470RawTensor TensorLibrary::get(const std::string &name, Format format, Channel channel)
471{
472 return RawTensor(find_or_create_raw_tensor(name, format, channel));
473}
474} // namespace test
475} // namespace arm_compute