概述
将一个 uint 类型的 tensor(numpy) 转换为 指定的 数据类型,根据需要 缩放 值
注意:
在有些情况会自动进行 归一化,如果 不想 进行归一化,可以用tf.cast()函数
语法
tf.image.convert_image_dtype(
image,
dtype,
saturate=False,
name=None
)
参数
- image:图像,numpy 或 tensor类型
- dtype:要转换的类型
- saturate=False:
返回值
- 转换成指定数据类型的图像(numpy或tensor类型)
注意:
如果 参数image 为整数,参数dtype 为 tf.float32 类型,在转换时,会自动进行 归一化 处理,将数据缩放到 0-1范围
相当于 除以255
例子 1
读取图片,并解码成tensor
import tensorflow as tf
import matplotlib.pyplot as plt
content_path=r"C:\Users\mym\.keras\datasets\YellowLabradorLooking_new.jpg"
img = tf.io.read_file(content_path)
img = tf.image.decode_image(img, channels=3)
将图片通过tf.image.convert_image_dtype()转码
img2 = tf.image.convert_image_dtype(img,tf.float32)
plt.imshow(img2)
np.max(img2),np.min(img2)
由于传入的是 整型 ,转换成 浮点型,会自动做归一化处理
相当于下面操作:
将图片直接除以255
img3=img/255
对比上面两个结果,会发现几乎相同(浮点运算会有些误差)
x=img2.numpy()-img3.numpy()
len(x[x>0.0000001]),len(x[x>0.00000001])
执行结果:
(0, 466825)
相差大于0.0000001的数量是0,相差大于0.00000001的数量是466825,可以理解为:相差是由于浮点运算造成误差,忽略不计
例子2
接上例,将上面的结果(归一化后),转换 int32型,会转换会原图片数据
z=tf.image.convert_image_dtype(img2,tf.int32)
z
转换后的结果,与原图相同
注意:
转换类型是:tf.int32,不能是tf.uint8