data_utils.py 8.7 KB

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