torcs_data_preparation.py 7.06 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 mxnet as mx
8
import numpy as np
9
from PIL import Image
10
import plyvel
11
from sklearn.cross_validation import train_test_split
12
13
14
import tarfile
import os

15
ARCHIVE = False
16
17
CHUNK_SIZE = 10000
LEVELDB_PATH = "/media/sveta/4991e634-dd81-4cb9-bf46-2fa9c7159263/TORCS_Training_1F"
18
19
20
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/"
21
22
23
24
25


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

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
    # leveldb_to_rec(start_date)
    read_from_recordio()
    # compute_train_mean()


def compute_train_mean():
    record = mx.recordio.MXRecordIO(RAW_PATH + "torcs_train.rec", "r")
    img_stats = []
    for i in range(50):
        item = record.read()
        header, img_as_array = mx.recordio.unpack_img(item)
        # img is RGB of shape (210, 280, 3)
        # img = Image.fromarray(img_as_array)
        # img.show()
        mean, std = cv2.meanStdDev(img_as_array)
        mean_as_img = Image.fromarray(mean)
        mean_as_img.show()
        img_stats.append(np.array([mean[::-1] / 255, std[::-1] / 255]))
    img_stats = np.mean(img_stats, axis=0)
    print(img_stats)


def read_from_recordio():
    record = mx.recordio.MXRecordIO(RAW_PATH + "torcs_train.rec", "r")
    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())


def leveldb_to_rec(start_date):
    train_record = mx.recordio.MXRecordIO(RAW_PATH + "torcs_train.rec", "w")
    test_record = mx.recordio.MXRecordIO(RAW_PATH + "torcs_test.rec", "w")
    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()
73
74

    for key, value in db:
75
76
        key_as_int = int(float(key))

77
78
79
        datum = datum.FromString(value)
        indicators = np.array(datum.float_data, dtype='f')
        indicators = normalize(indicators)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

        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")
113
114
115
116
117
118
119
120
121
122
123


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)

124
125
126
127
128
129
    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()
130

131
132
133
134
        os.remove(filename)
        current_time = datetime.datetime.now()
        elapsed_time = current_time - start_date
        print("Finished archiving. Total time spent: " + str(elapsed_time))
135
136
137
138
139
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


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


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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)


194
195
196
main()