[英]Proper way of resizing image for Deep Learning models
I'm a beginner in Deep Learning & Tensorflow. During the preprocessing part, I'm stucking again & again on that part where I have to resize the image with specific dimension for some specific NN architecture.我是深度学习和 Tensorflow 的初学者。在预处理部分,我一次又一次地停留在我必须为某些特定的 NN 体系结构调整图像的特定尺寸的部分。 I googled and tried different methods but in vain.
我用谷歌搜索并尝试了不同的方法,但没有成功。
For eg., I did following to resize image to 227 x 227 for AlexNet:例如,我按照以下步骤将 AlexNet 的图像大小调整为 227 x 227:
height = 227
width = 227
dim = (width, height)
x_train = np.array([cv2.resize(img, dim) for img in x_train[:,:,:]])
x_valid = np.array([cv2.resize(img, dim) for img in x_valid[:,:,:]])
x_train = tf.expand_dims(x_train, axis=-1)
x_valid = tf.expand_dims(x_valid, axis=-1)
I'm trying to resize the images with cv2 but after expanding, the dimensions come out to be:我正在尝试使用 cv2 调整图像的大小,但在展开后,尺寸变为:
(227, 227, 1)
whereas I want them to be:而我希望他们是:
(227, 227, 3)
So, is there any better way to do this?那么,有没有更好的方法来做到这一点?
The following line in your script is causing the problem脚本中的以下行导致了问题
x_train = np.array([cv2.resize(img, dim) for img in x_train[:,:,:]])
Change it to改成
x_train = np.array([cv2.resize(img, dim) for img in x_train])
One option for fasting do this can be creating a dataset with tf.data.Dataset
then writing a function for resizing images with tf.image.resize
like below:禁食的一种选择是使用
tf.data.Dataset
创建数据集,然后编写 function 以使用tf.image.resize
调整图像大小,如下所示:
import tensorflow as tf
import matplotlib.pyplot as plt
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data()
train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test))
HEIGHT = 227
WIDTH = 227
def resize_preprocess(image, label):
image = tf.image.resize(image, (HEIGHT, WIDTH)) / 255.0
return image, label
train_dataset = train_dataset.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
test_dataset = test_dataset.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
for image, label in train_dataset.take(1):
print(image.shape)
plt.imshow(image), plt.axis('off')
plt.show()
Output: Output:
(227, 227, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.