我先前编写的代码在单个图像上运行良好。但是现在我希望程序运行多个图像。我只需要提供文件夹名称作为参数即可。
我以这样的方式修改了代码:打开目录并保存图像,但出现错误
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]))
这是从文件夹读取图像的正确方法吗?如何对给定文件夹中的所有图像进行分类并给出每个图像的预测?
答案 0 :(得分:1)
根据您的答案,您应该执行以下操作:
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
数组附加了两个图像,并且您试图像只有一个图像那样对其进行整形。
此外,在for循环中迭代创建tf.Session
并始终加载图形是一种极其糟糕的做法。我将通过以下方式更改整个代码:
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]))