-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmnist.cpp
70 lines (60 loc) · 1.69 KB
/
mnist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <fstream>
#include "mnist.h"
#include <exception>
#include "textcolor.h"
#include <vector>
#include <iostream>
using namespace std;
struct BadMagic : public std::exception {
const char * what() const throw() { return "Bad magic number"; } };
int32_t readSwap(fstream& file) {
int32_t num;
file.read((char*)&num, sizeof(num));
return __builtin_bswap32(num);
}
MNISTLabels::MNISTLabels(int32_t magic) {
magicNumber = magic;
}
void MNISTLabels::loadFile(string name) {
fstream file(name.c_str(), ios::in|ios::binary);
int32_t magic_ = readSwap(file);
if (magic_ != magicNumber) throw BadMagic();
numItems = readSwap(file);
labels = new char[numItems];
file.read(labels, numItems);
file.close();
}
MNISTImages::MNISTImages(int32_t magic) {
magicNumber = magic;
}
void MNISTImages::loadFile(string name) {
fstream file(name.c_str(), ios::in|ios::binary);
int32_t magic_ = readSwap(file);
if (magic_ != magicNumber) throw BadMagic();
numImages = readSwap(file);
rows = readSwap(file);
cols = readSwap(file);
cout << "rows=" << rows << " cols=" << cols << "\n";
for (int i = 0; i < numImages; i++) {
char* pixels = new char[rows*cols];
file.read(pixels, rows*cols);
images.push_back(pixels);
}
file.close();
}
void MNISTImages::printImage(int index) {
char* pixels = images[index];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
uint8_t darkness = pixels[row*cols+col];
float levels = 255 - 232;
//float grey = darkness;
float greyLevel = (darkness/255.0) * levels;
int color = 255 - greyLevel;
textColor(color);
printf("█");
}
printf("\n");
}
textColor(7);
}