-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtransform.py
More file actions
39 lines (31 loc) · 1.08 KB
/
transform.py
File metadata and controls
39 lines (31 loc) · 1.08 KB
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
#!/usr/bin/python
# -*- coding:utf-8 -*-
import struct
import numpy as np
import PIL.Image
'''解析训练标签后得到数字并保存在解析的图片文件名中'''
def getTrainLabels():
f1 = open("mnist_data/train-labels.idx1-ubyte", 'rb')
buf1 = f1.read()
f1.close()
index = 0
magic, num = struct.unpack_from(">II", buf1, 0)
index += struct.calcsize('>II')
labs = []
labs = struct.unpack_from('>' + str(num) + 'B', buf1, index)
return labs
filename = 'mnist_data/train-images.idx3-ubyte'
binfile = open(filename, 'rb')
buf = binfile.read()
index = 0
magic, numImages, numRows, numColumns = struct.unpack_from('>IIII', buf, index)
index += struct.calcsize('>IIII')
for image in range(0, numImages):
im = struct.unpack_from('>784B', buf, index)
index += struct.calcsize('>784B')
im = np.array(im, dtype='uint8')
im = im.reshape(28, 28)
im = PIL.Image.fromarray(im)
label = getTrainLabels()
imagenumber = label[image]
im.save('mnist_train/%s_train_%s.bmp' % (imagenumber, image), 'bmp')