使用 Python 和 Keras 加载并显示图像

本文将展示如何使用 Keras 加载图像,并使用 matplotlib 库将其显示。

首先,你需要加载图像。可以使用 Keras 的 image.load_img 函数来完成此操作。该函数接受图像路径和目标大小作为参数。目标大小指定图像的宽度和高度。

from keras.preprocessing import image
test_image = image.load_img('E:/image/test/cats/cat.1451.jpg', target_size=(150, 150))

接下来,你需要将图像转换为 NumPy 数组。可以使用 Keras 的 image.img_to_array 函数来完成此操作。

test_image = image.img_to_array(test_image)

现在,你需要将图像扩展为四维张量,以便 Keras 模型可以处理它。可以使用 NumPy 的 expand_dims 函数来完成此操作。

test_image = np.expand_dims(test_image, axis=0)

最后,你需要将图像的值缩放到 0 到 1 之间。可以使用以下代码来完成此操作:

test_image = test_image / 255.0

现在,你已经准备好了将图像显示出来。可以使用 matplotlib 库的 imshow 函数来完成此操作。该函数接受一个 NumPy 数组作为参数。

import matplotlib.pyplot as plt

# 显示图像
plt.imshow(test_image[0])
plt.show()

运行以上代码即可显示图像。

完整代码:

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

# 加载测试图像
test_image = image.load_img('E:/image/test/cats/cat.1451.jpg', target_size=(150, 150))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
test_image = test_image / 255.0

# 显示图像
plt.imshow(test_image[0])
plt.show()

希望本文对你有所帮助!

使用 Python 和 Keras 加载并显示图像

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

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