导入图像预处理和可视化所需的库

from tensorflow.keras.preprocessing import image import numpy as np import matplotlib.pyplot as plt

定义执行图像识别的函数

def recognize_image(image_path): img = image.load_img(image_path, target_size=(150, 150)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img /= 255.0 # 将图像像素值归一化,与训练时相同

# 使用训练好的模型进行预测
predictions = cnn_model.predict(img)

# 获取预测概率最高的类别标签
class_index = np.argmax(predictions)
class_label = labels[class_index]

return img, class_label

将'image_path'替换为要识别的图像的路径

image_path = 'C:/Users/syy/Desktop/毕业设计/项目/flowers/image/Validation/image5.jpg'

执行图像识别并获取识别到的类别

img, recognized_class = recognize_image(image_path)

显示图像及其识别到的类别

plt.figure(figsize=(4, 3)) plt.imshow(img[0]) plt.title(f'图像识别为: {recognized_class}') plt.axis('off') plt.show()


原文地址: http://www.cveoy.top/t/topic/pghh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录