![](/img/trans.png)
[英]How to feed OpenCV image to a trained CNN model(add a new dimension) in Python?
[英]How to classify a new image with a trained CNN?
我按照教程在 MNIST 數據集上創建了一個帶有 Keras 的 CNN。 我想在我下載的全新圖像上測試我的 model。 我的理解是我必須將圖像轉換為黑白,然后將其轉換為 numpy 數組。 從那里我應該能夠將 numpy 數組輸入到 model.predict 但我得到一個錯誤。 有沒有一種簡單的方法可以通過簡單地將我的新圖像的路徑提供給 model 來在新圖像上測試我的 model? 下面是我試過的代碼
from PIL import Image
from numpy import asarray
img = Image.open("Eight.png") # open colour image
img = img.convert('1') # convert image to black and white
img.save('eight_BW.png')
# load the image and convert into
# numpy array
img = Image.open('eight_bw.png')
# asarray() class is used to convert
# PIL images into NumPy arrays
numpydata = asarray(img, dtype=int)
# <class 'numpy.ndarray'>
print(type(numpydata))
# shape
print(numpydata.shape)
model.predict(numpydata)
<class 'numpy.ndarray'> (55, 72)
ValueError: Input 0 of layer sequential_2 is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: [None, 72]
下面是 model 代碼:
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
batch_size = 128
num_classes = 10
epochs = 10
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])
hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
print("The model has successfully trained")
model.save('mnist.h5')
print("Saving the model as mnist.h5")
在numpydata = asarray(img, dtype=int)
和Tada 之后添加這兩行!
numpydata = np.expand_dims(numpydata, 0)
numpydata = np.expand_dims(numpydata, -1)
為什么:首先 model 接受一批圖像。 因此,您可以同時傳遞例如 32 張圖像。 但是,如果您只想通過 model 一張圖像,您的批次只有一張圖像,模型輸入形狀應為 (1, ..image_shape..) (開頭的額外維度已由numpydata = np.expand_dims(numpydata, 0)
)。 另一方面,即使您的圖像有一個通道(通道 == 1),您的圖像也應該具有三個維度(高度、寬度、通道),因此我們在末尾添加了額外的維度numpydata = np.expand_dims(numpydata, -1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.