Imported Upstream version 1.12.0
[platform/core/ml/nnfw.git] / tests / tools / tflite_run / src / bin_image.cc
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <iostream>
18 #include <fstream>
19
20 #include "bin_image.h"
21
22 BinImage::BinImage(unsigned int width, unsigned int height, unsigned int channels)
23   : _width(width), _height(height), _channels(channels)
24 {
25 }
26
27 BinImage::~BinImage() {}
28
29 void BinImage::loadImage(const std::string &filename)
30 {
31   std::ifstream fin(filename);
32
33   if (!fin)
34   {
35     std::cerr << "image filename is not specified. "
36               << "Input image will not be set." << std::endl;
37     return;
38   }
39
40   _image.reserve(_width * _height * _channels);
41
42   // Assuption: binary image is stored in the order of [H,W,C]
43   for (unsigned int i = 0; i < _width * _height * _channels; ++i)
44     _image.push_back(fin.get());
45 }
46
47 void BinImage::AssignTensor(TfLiteTensor *t)
48 {
49   float *p = t->data.f;
50   const int IMAGE_MEAN = 128;
51   const float IMAGE_STD = 128.0f;
52
53   // to prevent runtime exception
54   if (_image.size() < _width * _height * _channels)
55   {
56     std::cerr << "Input image size is smaller than the size required by the model."
57               << " Input will not be set." << std::endl;
58     return;
59   }
60
61   for (int x = 0; x < _width; ++x)
62   {
63     for (int y = 0; y < _height; ++y)
64     {
65       for (int c = 0; c < _channels; ++c)
66       {
67         *p++ = (_image[y * _width * _channels + x * _channels + c] - IMAGE_MEAN) / IMAGE_STD;
68       }
69     }
70   }
71 }