我以前写的代码工作很好的单一形象。但现在我想要的程序运行多个图像。我只需要为文件夹名作为参数。
我修改我的代码,它会打开一个目录,并保存图像这样的方式,但我得到一个错误
ValueError异常:不能重塑大小98304的阵列分成形状(1,128,128,3)
在x_batch=images.reshape(1,128,128,3)
:
images = []
for filename in os.listdir(folder):
image = cv2.imread(os.path.join(folder,filename))
image = cv2.resize(image, (128, 128))
images = np.append(images, image)
images = np.array(images, dtype=np.uint8)
images = images.astype('float32')
images = np.multiply(images, 1.0/255.0)
x_batch=images.reshape(1,128,128,3) <------ ERROR HERE
sess = tf.Session()
saver = tf.train.import_meta_graph('/home/kubuntu/SimpleCode/.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
y_pred = graph.get_tensor_by_name("y_pred:0")
x= graph.get_tensor_by_name("x:0")
y_true = graph.get_tensor_by_name("y_true:0")
y_test_images = np.zeros((1, 6))
feed_dict_testing= {x:x_batch, y_true:y_test_images}
result=sess.run(y_pred, feed_dict=feed_dict_testing)
print("Up :"+str(result[0][0]))
print("Down :"+str(result[0][1]))
print("Left :"+str(result[0][2]))
print("Right :"+str(result[0][3]))
print("Forward :"+str(result[0][4]))
print("Backward :"+str(result[0][5]))
这是从一个文件夹中读取图像的正确方法是什么?如何分类给定文件夹中的所有图像,并给出了每个图像的预测?
根据您的回答,你应该做到以下几点:
for filename in os.listdir(folder):
image = cv2.imread(os.path.join(folder,filename))
image = cv2.resize(image, (128, 128))
image = np.array(image, dtype=np.uint8)
image = image.astype('float32')
image = np.multiply(image, 1.0/255.0)
x_batch=image.reshape(1,128,128,3)
当你读第二图像,因为images
阵列有附加两个图像您试图重塑它像只有一个图像的代码失败。
此外,这是一个非常不好的做法,在反复创造tf.Session
for循环和负载图中的所有时间。我会改变以下列方式整个代码:
with tf.Session() as sess:
saver = tf.train.import_meta_graph('/home/kubuntu/SimpleCode/.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
y_pred = graph.get_tensor_by_name("y_pred:0")
x = graph.get_tensor_by_name("x:0")
y_true = graph.get_tensor_by_name("y_true:0")
y_test_images = np.zeros((1, 6))
for filename in os.listdir(folder):
image = cv2.imread(os.path.join(folder,filename))
image = cv2.resize(image, (128, 128))
image = np.array(image, dtype=np.uint8)
image = image.astype('float32')
image = np.multiply(image, 1.0/255.0)
x_batch=image.reshape(1,128,128,3)
feed_dict_testing= {x:x_batch, y_true:y_test_images}
result = sess.run(y_pred, feed_dict=feed_dict_testing)
print("Up :"+str(result[0][0]))
print("Down :"+str(result[0][1]))
print("Left :"+str(result[0][2]))
print("Right :"+str(result[0][3]))
print("Forward :"+str(result[0][4]))
print("Backward :"+str(result[0][5]))