torcs_data_preparation.py 8.87 KB
Newer Older
1
2
import caffe
from caffe.proto import caffe_pb2
3
4
import csv
import cv2
5
6
import datetime
import h5py
7
import math
8
import matplotlib.pyplot as plt
9
import mxnet as mx
10
import numpy as np
11
from PIL import Image
12
import plyvel
13
from sklearn.cross_validation import train_test_split
14
15
16
import tarfile
import os

17
18
TRAIN_LENGTH = 387851

19
20
21
TEST_REC = "torcs_test.rec"
TRAIN_REC = "torcs_train.rec"

22
ARCHIVE = False
23
24
CHUNK_SIZE = 10000
LEVELDB_PATH = "/media/sveta/4991e634-dd81-4cb9-bf46-2fa9c7159263/TORCS_Training_1F"
25
26
27
HDF5_PATH = "/media/sveta/4991e634-dd81-4cb9-bf46-2fa9c7159263/TORCS_HDF5_3/"
RAW_PATH = "/media/sveta/4991e634-dd81-4cb9-bf46-2fa9c7159263/TORCS_raw/"
EXAMPLES_PATH = "/media/sveta/4991e634-dd81-4cb9-bf46-2fa9c7159263/TORCS_examples/"
28

29
30
TRAIN_MEAN = [99.39394537, 110.60877108, 117.86127587]
TRAIN_STD = [42.04910545, 49.47874084, 62.61726178]
31
32
33
34

def main():
    start_date = datetime.datetime.now()

35
    # leveldb_to_rec(start_date)
36
    # read_from_recordio()
37
    # compute_train_mean()
38
39
40
    # test_normalization()
    # check_saved_labels()
    check_saved_images()
41
42
43


def compute_train_mean():
44
45
46
    record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_REC, "r")
    all_means = list()
    all_std = list()
47
    for i in range(TRAIN_LENGTH):
48
49
        if i % 1000 == 0:
            print(i)
50
51
52
53
        item = record.read()
        header, img_as_array = mx.recordio.unpack_img(item)
        # img is RGB of shape (210, 280, 3)
        mean, std = cv2.meanStdDev(img_as_array)
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
79
80
81
        all_means.append(mean)
        all_std.append(std)
        # img_stats.append(np.array([mean[::-1] / 255, std[::-1] / 255]))
    mean = np.mean(all_means, axis=0)
    print("MEAN")
    print(mean)
    std = np.mean(all_std, axis=0)
    print("STD")
    print(std)


def test_normalization():
    width = 280
    height = 210
    data_mean = np.asarray([[[a] * width] * height for a in TRAIN_MEAN]) # (3, 280, 210)
    data_std = np.asarray([[[a] * width] * height for a in TRAIN_STD])
    record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_REC, "r")
    item = record.read()
    header, img_as_array = mx.recordio.unpack_img(item) # (210, 280,3)
    img = Image.fromarray(img_as_array)
    img.show()

    normalized_img = (img_as_array - np.transpose(data_mean, (1, 2, 0)))/np.transpose(data_std, (1, 2, 0))
    plt.matshow(normalized_img[:,:,0])
    plt.show()

    plt.matshow(normalized_img[:,:,1])
    plt.show()
82

83
84
    plt.matshow(normalized_img[:,:,2])
    plt.show()
85
86

def read_from_recordio():
87
    record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_REC, "r")
88
89
90
91
92
93
94
95
96
97
98
    for i in range(50):
        item = record.read()
        header, img = mx.recordio.unpack_img(item)
        key = str(header[2])
        convert_to_image_and_save(img, key)
        labels_file = EXAMPLES_PATH + key + "_labels.csv"
        with open(labels_file, 'wb') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=' ',
                                    quotechar='|', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow(header[1].tolist())

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def check_saved_labels():
    record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_REC, "r")
    for i in range(TRAIN_LENGTH):
        item = record.read()
        header, img = mx.recordio.unpack_img(item)
        affordance = header[1].tolist()
        # if not any([True if a>=0.1 and a<=0.9 else False for a in affordance ]):
        if any(math.isnan(item) for item in affordance):
            print(affordance)

def check_saved_images():
    record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_LENGTH, "r")
    for i in range(TRAIN_LENGTH):
        item = record.read()
        header, img = mx.recordio.unpack_img(item)
        try:
            img = Image.fromarray(img)
            img.verify()
        except (IOError, SyntaxError) as e:
            print('Bad file:', i)


121
122

def leveldb_to_rec(start_date):
123
124
    train_record = mx.recordio.MXRecordIO(RAW_PATH + TRAIN_REC, "w")
    test_record = mx.recordio.MXRecordIO(RAW_PATH + TEST_REC, "w")
125
126
127
128
129
130
131
132
    keys = range(1, 484815)

    train_keys, test_keys = train_test_split(keys,test_size=0.2)

    print str(len(train_keys)) + " samples for training"
    print str(len(test_keys)) + " samples for testing"

    db, datum = read_db()
133
134

    for key, value in db:
135
136
        key_as_int = int(float(key))

137
138
139
        datum = datum.FromString(value)
        indicators = np.array(datum.float_data, dtype='f')
        indicators = normalize(indicators)
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

        image_data = caffe.io.datum_to_array(datum) # shape is (3, 210, 280)
        image_data = np.transpose(image_data, (1, 2, 0))  # shape is (210, 280, 3)
        image_data = image_data[:, :, ::-1]  # BGR to RGB

        # convert_to_image_and_save(image_data, key_as_str)

        header = mx.recordio.IRHeader(0, indicators, key_as_int, 0)
        image_record = mx.recordio.pack_img(header, image_data, img_fmt='.png')

        if key_as_int in train_keys:
            train_record.write(image_record)
        elif key_as_int in test_keys:
            test_record.write(image_record)
        else:
            raise Exception("Unknown key " + key)

        if key_as_int % 1000 == 0:
            print str(key_as_int) + "/" + str(len(keys))
            current_time = datetime.datetime.now()
            elapsed_time = current_time - start_date
            print("\t Total time spent: " + str(elapsed_time))


def read_db():
    db = plyvel.DB(LEVELDB_PATH, paranoid_checks=True, create_if_missing=False)
    datum = caffe_pb2.Datum()
    return db, datum


def convert_to_image_and_save(image_data, key):
    img = Image.fromarray(image_data)
    img.save(EXAMPLES_PATH + key + ".png")
173
174
175
176
177
178
179
180
181
182
183


def write_to_hdf5(images, indicators, file_idx, start_date):
    filename = HDF5_PATH + "/train_" + str(file_idx) + ".h5"
    with h5py.File(filename, 'w') as f:
        f['image'] = images
        f['predictions_label'] = indicators
        f.close()

    print("Finished dumping to file " + filename)

184
185
186
187
188
189
    if ARCHIVE:
        # archive and remove original file
        tar = tarfile.open(filename + ".tar.bz2", 'w:bz2')
        os.chdir(HDF5_PATH)
        tar.add("train_" + str(file_idx) + ".h5")
        tar.close()
190

191
192
193
194
        os.remove(filename)
        current_time = datetime.datetime.now()
        elapsed_time = current_time - start_date
        print("Finished archiving. Total time spent: " + str(elapsed_time))
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225


def normalize(indicators):
    indicators_normalized = np.zeros(len(indicators))

    indicators_normalized[0] = normalize_value(indicators[0], -0.5, 0.5)  # angle. Range: ~ [-0.5, 0.5]
    indicators_normalized[1] = normalize_value(indicators[1], -7, -2.5)  # toMarking_L. Range: ~ [-7, -2.5]
    indicators_normalized[2] = normalize_value(indicators[2], -2, 3.5)  # toMarking_M. Range: ~ [-2, 3.5]
    indicators_normalized[3] = normalize_value(indicators[3], 2.5, 7)  # toMarking_R. Range: ~ [2.5, 7]
    indicators_normalized[4] = normalize_value(indicators[4], 0, 75)  # dist_L. Range: ~ [0, 75]
    indicators_normalized[5] = normalize_value(indicators[5], 0, 75)  # dist_R. Range: ~ [0, 75]
    indicators_normalized[6] = normalize_value(indicators[6], -9.5, -4)  # toMarking_LL. Range: ~ [-9.5, -4]
    indicators_normalized[7] = normalize_value(indicators[7], -5.5, -0.5)  # toMarking_ML. Range: ~ [-5.5, -0.5]
    indicators_normalized[8] = normalize_value(indicators[8], 0.5, 5.5)  # toMarking_MR. Range: ~ [0.5, 5.5]
    indicators_normalized[9] = normalize_value(indicators[9], 4, 9.5)  # toMarking_RR. Range: ~ [4, 9.5]
    indicators_normalized[10] = normalize_value(indicators[10], 0, 75)  # dist_LL. Range: ~ [0, 75]
    indicators_normalized[11] = normalize_value(indicators[11], 0, 75)  # dist_MM. Range: ~ [0, 75]
    indicators_normalized[12] = normalize_value(indicators[12], 0, 75)  # dist_RR. Range: ~ [0, 75]
    indicators_normalized[13] = normalize_value(indicators[13], 0, 1)  # fast range ~ [0, 1]
    return indicators_normalized


def normalize_value(old_value, old_min, old_max):
    new_min = 0.1
    new_max = 0.9
    new_range = new_max - new_min
    old_range = old_max - old_min
    new_value = (((old_value - old_min) * new_range) / old_range) + new_min
    return new_value


226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def leveldb_to_hdf5(start_date):
    db, datum = read_db()
    all_images = []
    all_indicators = []
    file_idx = 1

    for key, value in db:
        datum = datum.FromString(value)
        indicators = np.array(datum.float_data, dtype='f')
        indicators = normalize(indicators)

        image_data = caffe.io.datum_to_array(datum)  # .astype(np.float32) # shape is (3, 210, 280)
        image_data = np.transpose(image_data, (1, 2, 0))
        image_data = image_data[:, :, ::-1]

        all_images.append(image_data)
        all_indicators.append(indicators)
        if len(all_images) >= CHUNK_SIZE:
            print("File " + str(file_idx))
            write_to_hdf5(all_images, all_indicators, file_idx, start_date)
            all_images = []
            all_indicators = []
            file_idx += 1
    # final file
    print("File " + str(file_idx))
    write_to_hdf5(all_images, all_indicators, file_idx, start_date)


254
255
256
main()