28 #include "tiny_dnn/util/util.h"
36 uint32_t magic_number;
42 inline void parse_mnist_header(std::ifstream& ifs,
mnist_header& header) {
43 ifs.read((
char*) &header.magic_number, 4);
44 ifs.read((
char*) &header.num_items, 4);
45 ifs.read((
char*) &header.num_rows, 4);
46 ifs.read((
char*) &header.num_cols, 4);
48 if (is_little_endian()) {
49 reverse_endian(&header.magic_number);
50 reverse_endian(&header.num_items);
51 reverse_endian(&header.num_rows);
52 reverse_endian(&header.num_cols);
55 if (header.magic_number != 0x00000803 || header.num_items <= 0)
56 throw nn_error(
"MNIST label-file format error");
57 if (ifs.fail() || ifs.bad())
61 inline void parse_mnist_image(std::ifstream& ifs,
62 const mnist_header& header,
68 const int width = header.num_cols + 2 * x_padding;
69 const int height = header.num_rows + 2 * y_padding;
71 std::vector<uint8_t> image_vec(header.num_rows * header.num_cols);
73 ifs.read((
char*) &image_vec[0], header.num_rows * header.num_cols);
75 dst.resize(width * height, scale_min);
77 for (uint32_t y = 0; y < header.num_rows; y++)
78 for (uint32_t x = 0; x < header.num_cols; x++)
79 dst[width * (y + y_padding) + x + x_padding]
80 = (image_vec[y * header.num_cols + x] / float_t(255)) * (scale_max - scale_min) + scale_min;
92 inline void parse_mnist_labels(
const std::string& label_file, std::vector<label_t> *labels) {
93 std::ifstream ifs(label_file.c_str(), std::ios::in | std::ios::binary);
95 if (ifs.bad() || ifs.fail())
96 throw nn_error(
"failed to open file:" + label_file);
98 uint32_t magic_number, num_items;
100 ifs.read((
char*) &magic_number, 4);
101 ifs.read((
char*) &num_items, 4);
103 if (is_little_endian()) {
104 reverse_endian(&magic_number);
105 reverse_endian(&num_items);
108 if (magic_number != 0x00000801 || num_items <= 0)
109 throw nn_error(
"MNIST label-file format error");
111 for (uint32_t i = 0; i < num_items; i++) {
113 ifs.read((
char*) &label, 1);
114 labels->push_back((label_t) label);
140 inline void parse_mnist_images(
const std::string& image_file,
141 std::vector<vec_t> *images,
147 if (x_padding < 0 || y_padding < 0)
148 throw nn_error(
"padding size must not be negative");
149 if (scale_min >= scale_max)
150 throw nn_error(
"scale_max must be greater than scale_min");
152 std::ifstream ifs(image_file.c_str(), std::ios::in | std::ios::binary);
154 if (ifs.bad() || ifs.fail())
155 throw nn_error(
"failed to open file:" + image_file);
157 detail::mnist_header header;
159 detail::parse_mnist_header(ifs, header);
161 for (uint32_t i = 0; i < header.num_items; i++) {
163 detail::parse_mnist_image(ifs, header, scale_min, scale_max, x_padding, y_padding, image);
164 images->push_back(image);
error exception class for tiny-dnn
Definition: nn_error.h:37