试图用自定义飞机图片测试我的 cifar-10 训练的 CNN



因此,在用python学习了Keras的CNN基础知识后,我尝试添加自己的飞机图片来测试我训练的程序。为此,我尝试导入 1920x1080 png 图像,经过一些研究,我找到了一种可能重塑图像的方法,但我收到以下错误消息:

回溯(最近一次调用(: 文件"C:/Users/me/Desktop/Programming Courses/Image_Classifier_Project/Model_Test.py",第 21 行,在 img = np.reshape(img, [1, 32, 32, 3]( 文件"<<strong>array_function内部结构>",第 6 行,重塑中 文件 "C:\Users\me\AppData\Roaming\Python\Python37\site-packagesumpy\core\fromnumeric.py",第 301 行,正在重塑 返回_wrapfunc(a, 'reshape', newshape, order=order( 文件"C:\Users\me\AppData\Roaming\Python\Python37\site-packagesumpy\core\fromnumeric.py",第 61 行,_wrapfunc 返回绑定(*args, **kwds( 值错误: 无法将大小为 1024 的数组调整为形状 (1,32,32,3(

图像是彩色的(训练图像也是如此(。

这是代码。我正在从文件调用我的训练结果。

from keras.datasets import cifar10
import keras.utils as utils
from keras.models import load_model
import numpy as np
import cv2
# Get Model Data
labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
(_, _), (x_test, y_test) = cifar10.load_data()
x_test = x_test.astype('float32') / 255.0
y_test = utils.to_categorical(y_test)
model = load_model('Classified.h5')
img = cv2.imread("a400m.png", 0)
img = cv2.resize(img, (32, 32))
img = np.reshape(img, [1, 32, 32, 3])
# results = model.evaluate(x=x_test, y=y_test)
# print("Loss: ", results[0])
# print("Accuracy", results[1])
test_image_data = np.asarray(img)
prediction = model.predict(x=test_image_data)
print("Prediction: ", labels[np.argmax(prediction)])
# max_index = np.argmax(prediction[0])
# print("Prediction: ", labels[max_index])

很抱歉代码混乱,只是尝试实现它,而不是从头开始

提前感谢!

首先,您的图像是彩色的,因此您需要将其加载为彩色图像:

img = cv2.imread("a400m.png", 1)  # 0 means grayscale

其次:

img = cv2.resize(img, (32, 32)) #give a shape of (32, 32, 3)

这条线将重塑您的形状图像(1920, 1080, 3)(32, 32, 3)形状。

最后,为了在该图像上进行预测,您需要扩展其暗淡,为此使用 numpy expand_dim功能 :

img = np.expand_dims(img, 0) #give a shape of (1, 32, 32, 3), 0 means first dim

最新更新