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. Image normalization: /=255. and /=127.5 - 1
/=255. Normalize the image, the range is [0, 1], /=127.5 - 1 normalize the image, the range is [-1, 1], these two are only different in normalization range, In order to see the two differences intuitively, the image is processed in two ways:
The histogram distribution of the two methods is the same, and the distribution of /=127.5 - 1 is relatively sparse, as shown in the following figure:
Reference blog:
https://blog.csdn.net/qq_20014079/article/details/82804374