我正在使用Inception v3,尝试使用MNIST JPG图像作为预测数据集。在将培训批次输入模型时,我遇到了一个问题。错误是由于形状。 X_batch的形状为(?,299,299),其中第一层需要的形状为(?,299,299,3)。在我的代码的不同部分,它替换了一些示例,我能够使用example_image = cv2.cvtColor(example_image,cv2.COLOR_GRAY2RGB)
将示例转换为RGB,从而使example_image.shape
为(299,299,3)。我的问题是,我是否可以使用cv2将X_batch转换为RGB或代码的一部分,以使X_batch的形状为(?,299,299,3)?
这是我需要进行转换的代码的一部分:
from random import sample
def prepare_batch(MNIST_paths_and_classes, batch_size):
batch_paths_and_classes = sample(MNIST_paths_and_classes, batch_size)
images = [mpimg.imread(path)[:, :] for path, labels in batch_paths_and_classes]
prepared_images = [prepare_image(image) for image in images]
X_batch = 2 * np.stack(prepared_images) - 1 # Inception expects colors ranging from -1 to 1
y_batch = np.array([labels for path, labels in batch_paths_and_classes], dtype=np.int32)
return X_batch, y_batch
X_batch, y_batch = prepare_batch(MNIST_paths_and_classes_train, batch_size=4)
X_batch =(4,299,299)
y_batch =(4,)
X_test, y_test = prepare_batch(MNIST_paths_and_classes_test, batch_size=len(MNIST_paths_and_classes_test))
X_test =(12000,299,299)
本节中的错误:
ValueError:无法为张量'X:0'输入形状为((?,299,299,3)'的形状(40,299,299)的值
n_epochs = 10
batch_size = 40
n_iterations_per_epoch = len(MNIST_paths_and_classes_train) // batch_size
with tf.Session() as sess:
init.run()
inception_saver.restore(sess, INCEPTION_V3_CHECKPOINT_PATH)
for epoch in range(n_epochs):
print("Epoch", epoch, end="")
for iteration in range(n_iterations_per_epoch):
print(".", end="")
X_batch, y_batch = prepare_batch(MNIST_paths_and_classes_train, batch_size)
sess.run(training_op, feed_dict={X: X_batch, y: y_batch, training: True})
acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})
print(" Train accuracy:", acc_train)
save_path = saver.save(sess, "./my_MNIST_model")
最佳答案
我不明白是什么让您感到困惑。正如您所说,cv2.cvtColor
会给出正确的形状,因此只需将X_batch
中的图像一张一张地转换即可。
X_batch_rgb = np.copy(X_batch)
for i in len(X_batch):
X_batch_rgb[i, ...] = cv2.cvtColor(X_batch[i, ...],cv2.COLOR_GRAY2RGB)
现在,
X_batch_rgb
数组具有所需的形状。关于python - 我可以对一批数据使用cv2.cvtColor(image,cv2.COLOR_GRAY2RGB)吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55779099/