在大部分图像识别问题中,通过图像数据预处理可以尽量避免模型收到无关因素的印象或者达到数据增强的目的,从而提高模型的准确性。其中,TensorFlow就提供了一些图像处理函数,来帮助对图像进行处理。下面我们简单介绍一些。
图像编解码处理
我们在电脑看到的彩色图片,虽然是三个维度,即RGB,但是图像存储并没有直接记录这些信息,而是通过压缩编的方式存储,如jpg编码等。要对图片三维数据处理,则需要解码。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
#读取原始图像
image=tf.gfile.FastGFile('.\mnist_data\horse.jpg','rb').read()
with tf.Session() as sess:
img_after_decode=tf.image.decode_jpeg(image)
print(img_after_decode.eval())
plt.imshow(img_after_decode.eval())
plt.show()
我们的原始图片如下,这是一幅我在新疆独库公路上拍摄的草原骏马的图片,手抖有点模糊。
图像翻转
对图像进行翻转可以很好增加图像的多样化,可以提升训练模型的泛化能力。翻转方式有上下翻转,左右翻转,随机翻转等。
我们看一个左右翻转的例子,可以看到骏马掉头了。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
image=tf.gfile.FastGFile('.\mnist_data\horse.jpg','rb').read()
with tf.Session() as sess:
img_after_decode=tf.image.decode_jpeg(image)
print(img_after_decode.eval())
flipped=tf.image.random_flip_left_right(img_after_decode)
plt.imshow(flipped.eval())
plt.show()
图像色彩调整
调整图像的色彩包括对图像的亮度、对比度、饱和度和色相进行调整。包括固定调整和随机调整等。现在看一个亮度调整如下:
adjusted_brightness=tf.image.random_brightness(img_after_decode,max_delta=0.9)
plt.imshow(adjusted_brightness.eval())
plt.show()
色彩调整的其他方法有
adjusted_contrast=tf.image.random_contrast(img_after_decode,0.2,18,) #对比度调整
adjusted_hue=tf.image.adjust_hue(img_after_decode,0.9) #色相调整
adjusted_saturation=tf.image.adjust_saturation(img_after_decode,6) #饱和度调整
图像标准化
图像标准化是将图像的亮度均值变为0,方差变为1.
adjusted_stand=tf.image.per_image_standardization(img_after_decode)
图像大小调整
resized=tf.image.resize_images(img_after_decode,[300,300],method=0) #调整大小
print(resized.dtype)
resized=np.asarray(resized.eval(),dtype="uint8")
# plt.imshow(resized)
croped=tf.image.resize_image_with_crop_or_pad(img_after_decode,300,300)#调整大小
padded=tf.image.resize_image_with_crop_or_pad(img_after_decode,1500,1500)#调整大小
central_cropped=tf.image.central_crop(img_after_decode,0.4) #调整大小
图像标注框
batched=tf.expand_dims(tf.image.convert_image_dtype(img_after_decode,tf.float32),0)
boxs=tf.constant([[[0.05,0.05,0.9,0.7],[0.2,0.3,0.5,0.5]]])
image_boxed=tf.image.draw_bounding_boxes(batched,boxs)
plt.imshow(image_boxed[0].eval())
总结
图像增强有利地增加了图像的多样性,使得训练模型有更多类型的数据可以使用,这样,使得模型能在更广范围内有作用,提升了模型的泛化能力。具体使用何种图像增强技术,这需要在具体问题中具体分析。在实践中摸索,在摸索中进步。