data_utils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. from configs import bcolors
  2. from utils import *
  3. from imageio import imread
  4. from imageio import imsave
  5. from PIL import Image
  6. from scipy import ndimage
  7. def preprocess(path, target_size):
  8. return preprocess_image(path, target_size)[0]
  9. def data_generator(xs, ys, target_size, batch_size=64):
  10. gen_state = 0
  11. while 1:
  12. if gen_state + batch_size > len(xs):
  13. paths = xs[gen_state: len(xs)]
  14. y = ys[gen_state: len(xs)]
  15. X = [preprocess(x, target_size) for x in paths]
  16. gen_state = 0
  17. else:
  18. paths = xs[gen_state: gen_state + batch_size]
  19. y = ys[gen_state: gen_state + batch_size]
  20. X = [preprocess(x, target_size) for x in paths]
  21. gen_state += batch_size
  22. yield np.array(X), np.array(y)
  23. def load_carla_train_data(path='', batch_size=32, shape=(100, 100)):
  24. xs = []
  25. ys = []
  26. start_load_time = time.time()
  27. with open(path + 'label_train.csv', 'r') as f:
  28. rows = len(f.readlines()) - 1
  29. f.seek(0)
  30. for i, line in enumerate(f):
  31. if i == 0:
  32. continue
  33. xs.append(path + 'center/' + line.split(',')[0])
  34. ys.append(float(line.split(',')[2]))
  35. # shuffle list of images
  36. c = list(zip(xs, ys))
  37. random.shuffle(c)
  38. xs, ys = zip(*c)
  39. train_xs = xs
  40. train_ys = ys
  41. train_generator = data_generator(train_xs, train_ys,
  42. target_size=shape,
  43. batch_size=batch_size)
  44. print(bcolors.OKBLUE + 'finished loading data, running time: {} seconds'.format(
  45. time.time() - start_load_time) + bcolors.ENDC)
  46. return train_generator, len(train_xs)
  47. def load_carla_test_data(path='', batch_size=32, shape=(100, 100)):
  48. xs = []
  49. ys = []
  50. start_load_time = time.time()
  51. with open(path + 'label_test.csv', 'r') as f:
  52. rows = len(f.readlines()) - 1
  53. f.seek(0)
  54. for i, line in enumerate(f):
  55. if i == 0:
  56. continue
  57. xs.append(path + 'center/' + line.split(',')[0])
  58. ys.append(float(line.split(',')[2]))
  59. # shuffle list of images
  60. c = list(zip(xs, ys))
  61. random.shuffle(c)
  62. xs, ys = zip(*c)
  63. train_xs = xs
  64. train_ys = ys
  65. train_generator = data_generator(train_xs, train_ys,
  66. target_size=shape,
  67. batch_size=batch_size)
  68. print(bcolors.OKBLUE + 'finished loading data, running time: {} seconds'.format(
  69. time.time() - start_load_time) + bcolors.ENDC)
  70. return train_generator, len(train_xs)
  71. def carla_load_steering_data(steering_log):
  72. df_steer = pd.read_csv(steering_log, usecols=['frame_id', 'steering_angle_change'], index_col=False)
  73. angle = np.zeros((df_steer.shape[0], 1))
  74. time = np.zeros((df_steer.shape[0], 1), dtype=np.int32)
  75. angle[:, 0] = df_steer['steering_angle_change'].values
  76. frame_arr = []
  77. for frame in df_steer['frame_id']:
  78. frame_arr.append(int(frame[:-4]))
  79. time[:, 0] = frame_arr
  80. data = np.append(time, angle, axis=1)
  81. return data
  82. def carla_load_frame_id(data):
  83. frame_id = []
  84. for i in range(0, data.shape[0]):
  85. frame_id.append(int(data[i, 0]))
  86. return frame_id
  87. def normalize_input(x):
  88. return x / 255.
  89. def exact_output(y):
  90. return y
  91. def carla_read_steerings(steering_log):
  92. steerings = defaultdict(list)
  93. with open(steering_log) as f:
  94. for line in f.readlines()[1:]:
  95. fields = line.split(",")
  96. timestamp, angle = int(str(fields[0])[:-4]), float(fields[2])
  97. steerings[timestamp].append(angle)
  98. return steerings
  99. def carla_read_images(image_folder, id, image_size):
  100. prefix = path.join(image_folder, 'center')
  101. img_path = path.join(prefix, '%08d.png' % id)
  102. imgs = []
  103. img = imread(img_path, pilmode='RGB')
  104. # Cropping
  105. crop_img = img[200:, :]
  106. # Resizing
  107. img = np.array(Image.fromarray(crop_img).resize(image_size))
  108. imgs.append(img)
  109. if len(imgs) < 1:
  110. print('Error no image at timestamp')
  111. print(id)
  112. img_block = np.stack(imgs, axis=0)
  113. if K.image_data_format() == 'channels_first':
  114. img_block = np.transpose(img_block, axes=(0, 3, 1, 2))
  115. return img_block
  116. def carla_read_images_augment(image_folder, id, image_size):
  117. prefix = path.join(image_folder, 'center')
  118. img_path = path.join(prefix, '%08d.png' % id)
  119. imgs = []
  120. img = imread(img_path, pilmode='RGB')
  121. # Flip image
  122. img = np.fliplr(img)
  123. # Cropping
  124. crop_img = img[200:, :]
  125. # Resizing
  126. # img = imresize(crop_img, output_shape=image_size)
  127. img = np.array(Image.fromarray(crop_img).resize(image_size))
  128. # Rotate randomly by small amount (not a viewpoint transform)
  129. rotate = random.uniform(-1, 1)
  130. img = ndimage.rotate(img, rotate, reshape=False)
  131. imgs.append(img)
  132. if len(imgs) < 1:
  133. print('Error no image at timestamp')
  134. print(id)
  135. img_block = np.stack(imgs, axis=0)
  136. if K.image_data_format() == 'channels_first':
  137. img_block = np.transpose(img_block, axes=(0, 3, 1, 2))
  138. return img_block
  139. def camera_adjust(angle, speed, camera):
  140. # Left camera -20 inches, right camera +20 inches (x-direction)
  141. # Steering should be correction + current steering for center camera
  142. # Chose a constant speed
  143. speed = 10.0 # Speed
  144. # Reaction time - Time to return to center
  145. # The literature seems to prefer 2.0s (probably really depends on speed)
  146. if speed < 1.0:
  147. reaction_time = 0
  148. angle = angle
  149. else:
  150. reaction_time = 2.0 # Seconds
  151. # Trig to find angle to steer to get to center of lane in 2s
  152. opposite = 20.0 # inches
  153. adjacent = speed * reaction_time * 12.0 # inches (ft/s)*s*(12 in/ft) = inches (y-direction)
  154. angle_adj = np.arctan(float(opposite) / adjacent) # radians
  155. # Adjust based on camera being used and steering angle for center camera
  156. if camera == 'left':
  157. angle_adj = -angle_adj
  158. angle = angle_adj + angle
  159. return angle
  160. def carla_data_generator(frame_id, steering_log, image_folder, unique_list, gen_type='train',
  161. batch_size=32, image_size=(128, 128), shuffle=True,
  162. preprocess_input=normalize_input, preprocess_output=exact_output):
  163. # Read all steering angles , get <frame_id, steering> map
  164. # -----------------------------------------------------------------------------
  165. steerings = carla_read_steerings(steering_log)
  166. # Data debug info
  167. # -----------------------------------------------------------------------------
  168. start = min(unique_list)
  169. end = max(unique_list)
  170. # print("sampling data from frame_id %d to %d" % (start, end))
  171. # print('frame_id len: ', len(frame_id))
  172. # print('steerings len: ', len(steerings))
  173. # While loop for data generator
  174. # -----------------------------------------------------------------------------
  175. # if shuffle:
  176. # random.shuffle(unique_list)
  177. i = 0
  178. x_buffer, y_buffer, buffer_size = [], [], 0
  179. while True:
  180. if i > end:
  181. i = start
  182. coin = random.randint(1, 2)
  183. if steerings[i] and i in frame_id:
  184. if gen_type == 'train':
  185. if coin == 1:
  186. image = carla_read_images(image_folder, i, image_size)
  187. else:
  188. image = carla_read_images_augment(image_folder, i, image_size)
  189. else:
  190. image = carla_read_images(image_folder, i, image_size)
  191. # Mean angle with a timestamp
  192. angle = np.repeat([steerings[i][0]], image.shape[0])
  193. # Adjust steering angle for horizontal flipping
  194. if gen_type == 'train' and coin == 2:
  195. angle = -angle
  196. # Adjust the steerings of the offcenter cameras
  197. x_buffer.append(image)
  198. y_buffer.append(angle)
  199. buffer_size += image.shape[0]
  200. if buffer_size >= batch_size:
  201. indx = list(range(buffer_size))
  202. if gen_type == 'train':
  203. np.random.shuffle(indx)
  204. x = np.concatenate(x_buffer, axis=0)[indx[:batch_size], ...]
  205. y = np.concatenate(y_buffer, axis=0)[indx[:batch_size], ...]
  206. x_buffer, y_buffer, buffer_size = [], [], 0
  207. yield preprocess_input(x.astype(np.float32)), preprocess_output(y)
  208. if shuffle:
  209. i = int(random.choice(unique_list))
  210. else:
  211. i += 1
  212. while i not in unique_list:
  213. i += 1
  214. if i > end:
  215. i = start