TensorFlow加载本地图像

 TensorFlow version: 2.5.0

# 方式一
import tensorflow as tf

img_path = 'cat.jpg'
img = tf.io.read_file(img_path) # 返回整个输入图像的Tensor,没有任何解析,是输入管道的第一步。
img = tf.io.decode_jpeg(img, channels=3) # 将JPEG编码的图像解码为uint8 tensor.
img = tf.image.resize(img, [224, 224]) # 调整图像大小(可以指定方法)type:float32 tensor
img = tf.expand_dims(img, axis=0) # 增加维度 type:float32 tensor

# 方式二

from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img

IMG_DIM = (224, 224)
sample_img_path = 'benign_test.png'
sample_img = load_img(sample_img_path, target_size=IMG_DIM)
sample_img_tensor = img_to_array(sample_img)
sample_img_tensor = np.expand_dims(sample_img_tensor, axis=0)
sample_img_tensor /= 255. # 像素归一化

1.tf.expand_dims():

2.图像归一化:/=255. 和 /=127.5 - 1

 /=255.对图像进行归一化,范围为[0, 1],/=127.5 - 1对图像进行归一化,范围为[-1, 1],这两种只是归一化范围不同,为了直观的看出2种区别,分别对图像进行两种处理:

 两种方式的直方图分布相同,/=127.5 - 1的分布较稀疏,如下图所示:

 参考博客:

https://blog.csdn.net/qq_20014079/article/details/82804374

https://blog.csdn.net/wind82465/article/details/108711150

https://blog.csdn.net/Forrest97/article/details/105895591

猜你喜欢

转载自blog.csdn.net/qq_40108803/article/details/118712351
今日推荐