利用Udacity模拟器实现自己的自动驾驶小车
1.软件下载
(1)Unity下载
使用Udacity模拟器需要安装Unity,下载链接:https://unity.cn/releases
下载后进行安装与注册
(2)Udacity模拟器下载
下载链接:https://github.com/udacity/self-driving-car-sim
选择链接中的 Version2, 2/07/17 (本文采用的Windows版本,如下图)
2.训练数据采集
解压缩下载的Udacity模拟器压缩包,点击运行beta_simulator.exe,运行后首先设置分辨率和图像质量,开始可设置为640×480和Fastest,如下图:
设置完成后,点击play进入模拟器,模拟器打开后点击TRAINING MODE(训练模式),如下图:
进入TRAINING MODE后点击右上角的RECORD选择训练数据保存的位置(注意保存位置要点选到文件夹上,不要选到文件夹内空白处),然后Select,如下图:
再次点击右上角RECOED,当其变成RECORDING时,就可以手动驾驶小车了,大概驾驶8,9分钟,点击右上角RECORDING,界面中间出现绿色Capturing Data,表示正在记录并存储图片与转向角,8,9分钟左中右三个摄像头共可采集2万多张图片,图片存储在IMG文件夹内,转向角存储在driving_log.csv中,如下图:
3.数据增强
(1)由于地图中左转较多,为防止小车易朝左偏出车道,对部分训练图片进行水平翻转,角度取负值。
def horizontal_flip(img, degree):
choice = np.random.choice([0, 1])
if choice == 1:
img, degree = cv2.flip(img, 1), -degree
return (img, degree)
(2)进行色彩空间转换并随机调整亮度。
def random_brightness(img, degree):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
alpha = np.random.uniform(low = 0.1, high = 1.0, size = None)
v = hsv[:, :, 2]
v = v * alpha
hsv[:, :, 2] = v.astype('uint8')
rgb = cv2.cvtColor(hsv.astype('uint8'), cv2.COLOR_HSV2RGB)
return(rgb, degree)
(3)由于训练数据中转向角为0的情况过多,将部分转向角为0的情况删除,设置丢弃率rate。
def discard_zero_steering(degrees, rate):
steering_zero_idx = np.where(degrees == 0)
steering_zero_idx = steering_zero_idx[0]
size_del = int(len(steering_zero_idx) * rate)
return np.random.choice(steering_zero_idx, size = size_del, replace = False)
4.网络训练
为实时查看迭代过程中loss变化,安装livelossplot
pip install livelossplot
网络训练(train.py):
### -*- coding: utf-8 -*-
import numpy as np
from keras.optimizers import SGD, Adam
from keras.layers.core import Dense, Dropout, Activation
from keras.layers import Conv2D, MaxPooling2D, Flatten, PReLU, BatchNormalization
from keras.models import Sequential, Model
from keras import backend as K
from keras.regularizers import l2
import os.path
import csv
import cv2
import glob
import pickle
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import json
from keras import callbacks
import math
from matplotlib import pyplot
from livelossplot import PlotLossesKeras
SEED = 13
def horizontal_flip(img, degree):
choice = np.random.choice([0, 1])
if choice == 1:
img, degree = cv2.flip(img, 1), -degree
return (img, degree)
def random_brightness(img, degree):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
alpha = np.random.uniform(low = 0.1, high = 1.0, size = None)
v = hsv[:, :, 2]
v = v * alpha
hsv[:, :, 2] = v.astype