1 // Copyright (C) 2018 Intel Corporation
3 // SPDX-License-Identifier: Apache-2.0
9 #include <MnistUbyte.h>
11 using namespace FormatReader;
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;
22 MnistUbyte::MnistUbyte(const std::string &filename) {
23 std::ifstream file(filename, std::ios::binary);
24 if (!file.is_open()) {
28 int number_of_images = 0;
31 file.read(reinterpret_cast<char *>(&magic_number), sizeof(magic_number));
32 magic_number = reverseInt(magic_number);
33 if (magic_number != 2051) {
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;
49 size_t size = _width * _height * 1;
51 _data.reset(new unsigned char[size], std::default_delete<unsigned char[]>());
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;