访问量: 10 次浏览
在这篇文章中,我们将看到如何用Python在TensorFlow中加载图像。
对于使用Tenserflow加载图像,我们使用 tf.keras.utils.load\_img 函数,它从一个特定的提供的路径加载PIL格式的图像。
PIL是一个Python图像库,使你的Python解释器能够访问图像处理功能。这个库提供了广泛的文件格式兼容性,一个富有成效的内部表示,以及一些强大的图像处理功能。
主要的图像库是为快速访问一些基本像素格式的信息而建立的。它应该作为一个广泛的图像处理工具的一个强有力的起点。
tf.keras.utils.load\_img我们可以在 tf.keras.utils.load\_img 函数中设置各种参数来加载图片。
path:所需图像的路径
grayscale:如果想加载灰度格式的图像,设置为 “true”。
color\_mode:在加载图像时设置各种颜色模式。默认为RGB。
target\_size:用于加载所需目标尺寸的图像。尺寸格式: (Image_height, Image_width)
interpolation:设置为所需的插值。默认为’最近的’。
keep\_aspect\_ratio:布尔值,表示是否在不扭曲长宽比的情况下调整照片的大小。
在调整大小之前,图像在中间被裁剪成所需的长宽比。
# Loading the required libraries
import tensorflow as tf
# Defining the path to the image
# which is to be loaded.
# The image_path shall be changed
# according to the requirement.
image_path = '/content/model_3.png'
# Calling the load_img function
# from the imported libraries.
# This return an image in PIL
# Format
image_loaded = tf.keras.utils.load_img(image_path)
# Printing the obtained image.
image_loaded
输出:

加载灰度图像的步骤与上面提到的相同,只是在加载图像时,我们需要设置参数 grayscale = True 。
# Loading the required libraries
import tensorflow as tf
# Defining the path to the image
# which is to be loaded.
image_path = '/content/model_3.png'
# Calling the load_img function from
# the imported libraries. This
# return an image in PIL
# Format
image_loaded = tf.keras.utils.load_img(image_path,
grayscale=True)
# Printing the obtained image.
image_loaded
输出:

在这种情况下,我们将以不同的目标尺寸加载我们的图像。
# Loading the required libraries
import tensorflow as tf
# Defining the path to the image
# which is to be loaded.
image_path = '/content/model_3.png'
# Calling the load_img function from the
# imported libraries. This return an
# image in PIL Format
image_loaded_1 = tf.keras.utils.load_img(image_path)
# Specifying size for the second Image
# Target size = (200,300)
image_loaded_2 = tf.keras.utils.load_img(image_path,
target_size=(200,
300))
# Printing the obtained image.
print("Size of Image 1: ", image_loaded_1.size)
print("Size of Image 2: ", image_loaded_2.size)
image_loaded_2.save('/content/out.png')
输出:

