【问题标题】:If image has (28,28,3) shape, how do i convert it to (28.28,1)?如果图像具有 (28,28,3) 形状,我如何将其转换为 (28.28,1)?
【发布时间】:2020-08-16 12:40:58
【问题描述】:

我正在使用手写数字的 mnist 数据集,并试图预测我写的数字。问题是我的数字是 (28,28,3) 的形状,而我的神经网络的预期形状是 (28,28,1)。如何转换?

我的代码:

import tensorflow as to
from tensorflow import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import cv2

data = mnist.load_data()
(x_train, y_train), (x_test, y_test) = data

classes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

x_train = x_train / 255
x_test = x_test / 255

model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))

model.compile(
     optimizer='adam',
     loss='sparse_categorical_crossentropy',
     metrics=['accuracy']
)

model.fit(x_train, y_train, epochs=7)
test_loss, test_acc = model.evaluate(x_test, y_test)
print('\nTest Loss:', test_loss)
print('Test accuracy:', test_acc)

img = Image.open("7.jpg").convert('L')
img_array = cv2.imread('7.jpg')
new_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
new_array = cv2.resize(new_array, (28,28))
print(new_array.shape)
print(x_test[0].shape)
plt.imshow(new_array, cmap='gray')
plt.show()

predictions = model.predict(new_array)

plt.grid(False)
plt.imshow(new_array, cmap='gray')
plt.title("Prediction: " + classes[np.argmax(predictions)])
plt.show()

【问题讨论】:

  • 您想将色彩空间缩小为黑白?
  • 如果您想将颜色深度从 24 位(3 通道)降低到 8 位(1 通道),请使用 cvtColor 将图像转换为灰度。如果您想进一步将信息减少到黑白(1 通道)阈值灰度输出。
  • 使用 cvtColor 后,它说:预期 flatten_input 有 3 个维度,但得到的数组形状为 (28, 28)
  • 如果没有任何代码,很难猜出错误出在哪里。我的猜测是您给cvtColor 提供了一个坏垫子和/或提供了错误的转换代码。
  • 刚刚添加了我的代码。感谢您的帮助????????

标签: python numpy opencv machine-learning mnist


【解决方案1】:

即使你想要一个 (28,28) 形状,张量也需要有 3 个维度,所以你必须将其扩展为 (28,28,1)。这样的事情就足够了:

new_array = cv2.resize(new_array, (28,28,1))

或使用new_array=new_array[..., None] 扩展它。

【讨论】:

  • 使用后:new_array=new_array[..., None] 我收到一个错误:预期 flatten_input 的形状为 (28, 28) 但得到的数组的形状为 (28, 1)
  • 我建议的第一个选项怎么样?还有错误来自哪里?
【解决方案2】:

假设 img 的形状为 (28, 28, 3),您可以这样做:

gray = cv2. cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.expand_dims(gray, 2)

这会将其转换为 (28, 28, 1) 的形状

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2020-01-07
    • 2020-05-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多