Keras 图像加载与显示:使用 Python 代码加载并展示图像
使用 Keras 加载并显示图像
本文将介绍如何使用 Keras 库加载图像并使用 matplotlib 库显示图像。我们将展示一个简单的示例,演示如何加载图像、预处理并显示它。
1. 导入必要的库
from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
2. 加载图像
test_image = image.load_img('E:/image/test/cats/cat.1451.jpg', target_size=(150, 150))
3. 预处理图像
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
test_image = test_image / 255.0
4. 显示图像
plt.imshow(test_image[0])
plt.axis('off')
plt.show()
代码解释:
image.load_img()函数加载图像并将其调整为指定的大小。image.img_to_array()函数将图像转换为 NumPy 数组。np.expand_dims()函数在数组的第一个维度上添加一个新的维度,以使其与 Keras 模型的输入形状兼容。test_image / 255.0将图像像素值缩放到 0 到 1 之间,以进行标准化处理。plt.imshow()函数显示图像。plt.axis('off')函数隐藏坐标轴。plt.show()函数显示图像。
运行代码后,你将看到加载的图像被显示出来。
原文地址: https://www.cveoy.top/t/topic/pcAm 著作权归作者所有。请勿转载和采集!