This repository was archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage.py
More file actions
78 lines (61 loc) · 2.16 KB
/
package.py
File metadata and controls
78 lines (61 loc) · 2.16 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
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
70
71
72
73
74
75
76
77
78
"""
Package a directory of sprites into a numpy serialized file (.npy) and a label
array as another (.npy)
"""
import sys
import os
from os import listdir
from os.path import isfile, join, isdir
import matplotlib.image as mpimg
import numpy as np
import traceback
def store_n_label(srcDir,images,label,recCount):
"""
Recursively read in all images and generate labels
images is in format of { key: { 'img': np.array, 'dir': string, 'lbl': string }}
labels are generated from the directory hierarchy, appended by '_'.
"""
if recCount < 0:
return images
for f in listdir(srcDir):
if isdir(join(srcDir,f)):
images = store_n_label(join(srcDir,f),images,label + '_' + f,recCount - 1)
elif isfile(join(srcDir,f)) and not f == 'desktop.ini':
images[f] = {}
images[f]['lbl'] = label
images[f]['dir'] = srcDir
origImg = mpimg.imread(join(srcDir,f))
resImg = np.reshape(origImg, (1,) + origImg.shape)
images[f]['img'] = resImg
return images
def package(destFileName, images):
"""
Given image dictionary and location, save numpy files
"""
labelList = []
first = True
for key in images.keys():
if first:
print(images[key]['img'].shape)
imgSet = images[key]['img']
first = False
else:
imgSet = np.concatenate((imgSet,images[key]['img']),axis=0)
labelList.append(images[key]['lbl'])
print(join(images[key]['dir'],key))
print(images[key]['lbl'])
np.save(destFileName + '_image.npy',np.array(imgSet))
np.save(destFileName + '_label.npy',np.array(labelList))
if __name__ == '__main__':
# Get command-line args
if len(sys.argv) != 5:
print('{} sourceDirectory destinationFileName rootLabel recursiveLimit'.format(sys.argv[0]))
exit()
else:
sourceDirectory = sys.argv[1]
destinationFileName = sys.argv[2]
rootLabel = sys.argv[3]
recursiveLimit = int(sys.argv[4])
# Save the images
images = store_n_label(sourceDirectory,{},rootLabel,recursiveLimit)
package(destinationFileName,images)