예제 #1
0
def main():

    # This will get number of pixels in each image (they must all be the same!)
    imgsize = 0

    # Read in images from car, convert to grayscale, scale down, and flatten for use as input
    images = []
    for k in range(SAFESIZE):

        image = loadgray(IMAGEDIR + '/image%03d.png' % k)

        imgsize = np.prod(image.shape)
        images.append(image)

    # All but last image is safe (01 = no-crash; 10 = crash)
    targets = []
    for k in range(SAFESIZE - 1):
        targets.append([0, 1])
    targets.append([1, 0])

    # with tf.Graph().as_default():

    x = tf.compat.v1.placeholder('float', [None, imgsize])  # car FPV images
    y = tf.compat.v1.placeholder('float',
                                 [None, 2])  # 01 = no-crash; 10 = crash

    output = inference(x, imgsize, 2)

    cost = loss(output, y)

    global_step = tf.Variable(0, name='global_step', trainable=False)

    train_op = training(cost, global_step)

    sess = tf.compat.v1.Session()

    init_op = tf.compat.v1.global_variables_initializer()

    sess.run(init_op)

    # Training cycle
    for epoch in range(training_epochs):

        # Fit training using batch data
        sess.run(train_op, feed_dict={x: images, y: targets})

        # Compute average loss
        avg_cost = sess.run(cost, feed_dict={x: images, y: targets})

        # Display logs per epoch step
        if epoch % display_step == 0:
            print('Epoch:', '%04d' % epoch, 'cost =',
                  '{:.9f}'.format(avg_cost))

        print('Optimization Finished; saving weights to ' + PARAMFILE)
        params = [
            sess.run(param) for param in tf.compat.v1.trainable_variables()
        ]

        pickle.dump(params, open(PARAMFILE, 'wb'))
# go forward
car_controls.throttle = INITIAL_THROTTLE
car_controls.steering = 0
client.setCarControls(car_controls)

# Load saved training params as ordinary NumPy
W, b = pickle.load(open('params.pkl', 'rb'))

with tf.Graph().as_default():

    # Placeholder for an image
    x = tf.placeholder('float', [None, IMGSIZE])

    # Our inference engine, intialized with weights we just loaded
    output = inference(x, IMGSIZE, 2, W, b)

    # TensorFlow initialization boilerplate
    sess = tf.Session()
    init_op = tf.global_variables_initializer()
    sess.run(init_op)

    # Once the brakes come on, we need to keep them on for a while before exiting; otherwise,
    # the vehicle will resume moving.
    brakingCount = 0

    # Loop until we detect a collision
    while True:

        # Get RGBA camera images from the car
        responses = client.simGetImages(