试图用定制的飞机图片测试我的cifar10训练过的CNN

2024-04-26 13:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Traceback (most recent call last): File "C:/Users/me/Desktop/Programming Courses/Image_Classifier_Project/Model_Test.py", line 21, in img = np.reshape(img, [1, 32, 32, 3]) File "<array_function internals>", line 6, in reshape File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\numpy\core\fromnumeric.py", line 301, in reshape return _wrapfunc(a, 'reshape', newshape, order=order) File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\numpy\core\fromnumeric.py", line 61, in _wrapfunc return bound(*args, **kwds) ValueError: cannot reshape array of size 1024 into shape (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])

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

提前谢谢


Tags: inpytest图像importnumpyimgmodel
1条回答
网友
1楼 · 发布于 2024-04-26 13:11:45

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

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)形状

最后,为了预测该图像,您需要扩展其dim,为此使用numpy expand_dim功能:

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

相关问题 更多 >