我尝试按照教程TensorFlow 2 初学者快速入门进行操作。确实,我成功运行了它。
然后我在Paint中创建了一张图像(7.jpg, 200×200像素)。
现在我想让模型尝试猜测这个数字是什么。我尝试处理图像:
import tensorflow as tfimport numpy as npmnist = tf.keras.datasets.mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 教程示例中包含epochs=5,但为了运行得更快并得到更小的输出,我设置为1model.fit(x_train, y_train, epochs=1) img_path = "7.jpg"img_raw = tf.io.read_file(img_path)img_tensor = tf.image.decode_image(img_raw)img_final = tf.image.resize(img_tensor, [28, 28])img_final = img_final / 255.0print("img_final.shape =", img_final.shape)predict = model.predict(img_final)
然后我得到了以下输出:
Train on 60000 samples 60000/60000 [==============================] - 3s 52us/sample - loss: 0.3013 - accuracy: 0.9120 img_final.shape = (28, 28, 3) Traceback (most recent call last): File "main.py", line 33, in <module> predict = model.predict(img_final) File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 909, in predict use_multiprocessing=use_multiprocessing) File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 462, in predict steps=steps, callbacks=callbacks, **kwargs) File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 396, in _model_iteration distribution_strategy=strategy) File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 594, in _process_inputs steps=steps) File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 2472, in _standardize_user_data exception_prefix='input') File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_utils.py", line 574, in standardize_input_data str(data_shape)) ValueError: Error when checking input: expected flatten_input to have shape (28, 28) but got array with shape (28, 3)
我添加了print("img_final.shape =", img_final.shape)
来查看输入图像的形状。我看到img_final.shape = (28, 28, 3)
。
我知道数字3
是通道数。根据文档tf.io.decode_image:
注意:decode_gif返回一个4-D数组[num_frames, height, width, 3],而decode_bmp, decode_jpeg和decode_png返回3-D数组[height, width, num_channels]。
所以,我有一个3-D数组的图像,但模型期待一个形状为(28, 28)的数组作为输入。
我怎样才能将其转换为(28, 28)
?我需要将其转换为单色还是进行其他处理?
更新:根据Ronald和Taras的回答,我添加了转换为灰度的代码和一些打印。现在我有:
print("img_final.shape =", img_final.shape)img_final = tf.image.rgb_to_grayscale(img_final)print("grayscale img_final.shape =", img_final.shape)img_final = tf.expand_dims(img_final[:, :, :1], axis=0)print("expand_dims img_final.shape =", img_final.shape)predict = model.predict(img_final)
以及输出:
img_final.shape = (28, 28, 3) grayscale img_final.shape = (28, 28, 1) expand_dims img_final.shape = (1, 28, 28, 1)Traceback (most recent call last): File "main.py", line 42, in <module> ...ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 28, 28, 1)
回答:
mnist数据库只有灰度图像,因此它们只有一个颜色通道。所以,是的,你需要通过将3个通道(我猜是RGB)转换为灰度来使其成为单色。你可以使用
tf.image.rgb_to_grayscale(images)
你可以查看文档以获取更多关于此的信息:tf.image.rgb_to_grayscale文档