我一直在研究 MNIST 数据集,以学习如何在我的深度学习课程中使用 Tensorflow 和 Python。
我想使用tensorflow将MNIST的大小调整为22和22,然后我训练它,但我不知道怎么办?
你能帮我吗?
简短回答
使用
tf.image.resize
(而不是 resize_images
)。其他提供的链接不再存在。更新了链接。
长答案
MNIST
中的tf.keras.datasets.mnist
是以下形状
(batch_size, 28 , 28)
这是完整的实现。请阅读代码附带的评论。
(x_train, y_train), (_, _) = tf.keras.datasets.mnist.load_data()
# expand new axis, channel axis
x_train = np.expand_dims(x_train, axis=-1)
# [optional]: we may need 3 channel (instead of 1)
x_train = np.repeat(x_train, 3, axis=-1)
# it's always better to normalize
x_train = x_train.astype('float32') / 255
# resize the input shape , i.e. old shape: 28, new shape: 32
x_train = tf.image.resize(x_train, [32,32]) # if we want to resize
print(x_train.shape)
# (60000, 32, 32, 3)
TheRevanchist 的答案是正确的。但是,对于 mnist 数据集,您首先需要重塑 mnist 数组,然后再将其发送到 tf.image.resize_images():
import tensorflow as tf
import numpy as np
import cv2
mnist = tf.contrib.learn.datasets.load_dataset("mnist")
batch = mnist.train.next_batch(10)
X_batch = batch[0]
batch_tensor = tf.reshape(X_batch, [10, 28, 28, 1])
resized_images = tf.image.resize_images(batch_tensor, [22,22])
上面的代码取出一批 10 mnist 图像,并将它们从 28x28 图像重塑为 22x22 张量流图像。
如果你想显示图像,你可以使用opencv和下面的代码。 resized_images.eval() 将张量流图像转换为 numpy 数组!
with tf.Session() as sess:
numpy_imgs = resized_images.eval(session=sess) # mnist images converted to numpy array
for i in range(10):
cv2.namedWindow('Resized image #%d' % i, cv2.WINDOW_NORMAL)
cv2.imshow('Resized image #%d' % i, numpy_imgs[i])
cv2.waitKey(0)
您尝试过 tf.image.resize_image 吗?
方法:
resize_images(images, size, method=ResizeMethod.BILINEAR,
align_corners=False)
其中 images 是一批图像,size 是确定新高度和宽度的向量张量。您可以在此处查看完整文档:https://www.tensorflow.org/api_docs/python/tf/image/resize_images
opencv的
cv2.resize()
在每个图像的 for 循环内部添加此行
cv2.resize(source_image, (22, 22))
def resize(mnist):
train_data = []
for img in mnist.train._images:
resized_img = cv2.resize(img, (22, 22))
train_data.append(resized_img)
return train_data