Publishing R3
[platform/upstream/dldt.git] / inference-engine / samples / common / format_reader / MnistUbyte.cpp
1 // Copyright (C) 2018 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0
4 //
5
6 #include <fstream>
7 #include <iostream>
8 #include <string>
9 #include <MnistUbyte.h>
10
11 using namespace FormatReader;
12
13 int MnistUbyte::reverseInt(int i) {
14     unsigned char ch1, ch2, ch3, ch4;
15     ch1 = (unsigned char) (i & 255);
16     ch2 = (unsigned char) ((i >> 8) & 255);
17     ch3 = (unsigned char) ((i >> 16) & 255);
18     ch4 = (unsigned char) ((i >> 24) & 255);
19     return (static_cast<int>(ch1) << 24) + (static_cast<int>(ch2) << 16) + (static_cast<int>(ch3) << 8) + ch4;
20 }
21
22 MnistUbyte::MnistUbyte(const std::string &filename) {
23     std::ifstream file(filename, std::ios::binary);
24     if (!file.is_open()) {
25         return;
26     }
27     int magic_number = 0;
28     int number_of_images = 0;
29     int n_rows = 0;
30     int n_cols = 0;
31     file.read(reinterpret_cast<char *>(&magic_number), sizeof(magic_number));
32     magic_number = reverseInt(magic_number);
33     if (magic_number != 2051) {
34         return;
35     }
36     file.read(reinterpret_cast<char *>(&number_of_images), sizeof(number_of_images));
37     number_of_images = reverseInt(number_of_images);
38     file.read(reinterpret_cast<char *>(&n_rows), sizeof(n_rows));
39     n_rows = reverseInt(n_rows);
40     _height = (size_t) n_rows;
41     file.read(reinterpret_cast<char *>(&n_cols), sizeof(n_cols));
42     n_cols = reverseInt(n_cols);
43     _width = (size_t) n_cols;
44     if (number_of_images > 1) {
45         std::cout << "[MNIST] Warning: number_of_images  in mnist file equals " << number_of_images
46                   << ". Only a first image will be read." << std::endl;
47     }
48
49     size_t size = _width * _height * 1;
50
51     _data.reset(new unsigned char[size], std::default_delete<unsigned char[]>());
52     size_t count = 0;
53     if (0 < number_of_images) {
54         for (int r = 0; r < n_rows; ++r) {
55             for (int c = 0; c < n_cols; ++c) {
56                 unsigned char temp = 0;
57                 file.read(reinterpret_cast<char *>(&temp), sizeof(temp));
58                 _data.get()[count++] = temp;
59             }
60         }
61     }
62
63     file.close();
64 }