我尝试使用以下代码在Python和Tensorflow中编写自动驾驶汽车:
import tensorflow as tf
from PIL import ImageGrab
import numpy as np
import pyautogui as pag
import time
x_p = tf.placeholder(tf.uint8)
y_p = tf.placeholder(tf.float32)
weights = [tf.Variable(tf.random_normal([5,5,3,32],0.1)),
tf.Variable(tf.random_normal([5,5,32,64],0.1)),
tf.Variable(tf.random_normal([5,5,64,128],0.1)),
tf.Variable(tf.random_normal([25*25*128,1064],0.1)),
tf.Variable(tf.random_normal([1064,1],0.1))]
def CNN(x, weights):
output = tf.nn.conv2d(x, weights[0], [1,1,1,1], 'SAME')
output = tf.nn.relu(output)
output = tf.nn.conv2d(output, weights[1], [1,2,2,1], 'SAME')
output = tf.nn.relu(output)
output = tf.nn.conv2d(output, weights[2], [1,2,2,1], 'SAME')
output = tf.nn.relu(output)
output = tf.reshape(output, [-1,25*25*128])
output = tf.matmul(output, weights[3])
output = tf.nn.relu(output)
output = tf.matmul(output, weights[4])
output = tf.reduce_sum(output)
return output
prediction = CNN(tf.cast(x_p, tf.float32), weights)
saver = tf.train.Saver()
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
saver.restore(sess, 'saved/model.ckpt')
for t in range(5):
print(t+1)
time.sleep(1)
while True:
x = ImageGrab.grab()
x = x.resize((100,100))
x = np.asarray(x)
output = sess.run(prediction, feed_dict={x_p:[x]})
print(output)
if output < 0.5 and output > 1.5:
pag.keyDown('W')
pag.keyUp('S')
pag.keyUp('D')
pag.keyUp('A')
elif output < 1.5 and output > 2.5:
pag.keyUp('W')
pag.keyDown('S')
pag.keyUp('D')
pag.keyUp('A')
elif output < 2.5 and output > 3.5:
pag.keyDown('W')
pag.keyUp('S')
pag.keyDown('D')
pag.keyUp('A')
elif output < 3.5 and output > 4.5:
pag.keyDown('W')
pag.keyUp('S')
pag.keyUp('D')
pag.keyDown('A')
elif output < 4.5 and output > 5.5:
pag.keyDown('W')
pag.keyUp('S')
pag.keyDown('D')
pag.keyUp('A')
elif output < 5.5 and output > 6.5:
pag.keyDown('W')
pag.keyUp('S')
pag.keyUp('D')
pag.keyDown('A')
elif output < 6.5 and output > 7.5:
pag.keyUp('W')
pag.keyDown('S')
pag.keyDown('D')
pag.keyUp('A')
elif output < 7.5 and output > 8.5:
pag.keyUp('W')
pag.keyDown('S')
pag.keyUp('D')
pag.keyDown('A')
else:
pag.keyUp('W')
pag.keyUp('S')
pag.keyUp('D')
pag.keyUp('A')
但问题是只有else语句触发,即使输出(例如)值为1.3。我能够发现问题是由if语句中的变量输出引起的,但我没有设法解决问题。
答案 0 :(得分:0)
你的if语句有问题。
if output < 0.5 and output > 1.5:
您的输出不能低于0.5,同时优于1.5。所以if语句一直都是错误的。
所有其他elif的问题都是一样的
我想你想写:
if output > 0.5 and output < 1.5: