Python 图像识别函数定义 - 使用 CNN 模型识别图像类别
定义执行图像识别的函数
定义一个函数,用于加载图像、进行预测并返回识别结果
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 = '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/pghp 著作权归作者所有。请勿转载和采集!