本文主要是介绍Tensorflow图像处理相关操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#对图像的处理import matplotlib.pyplot as plt
import tensorflow as tf#读取图像的原始数据
image_raw_data=tf.gfile.FastGFile("./path/to/picture/timg.jpg",'rb').read()with tf.Session() as sess:#将图像用jpeg格式解码从而得到图像对应的三维矩阵,Tensorflow 还提供了tf.image_decode_png 函数对png格式的图像#机械性解码。解码之后的结果为一个张量img_data=tf.image.decode_jpeg(image_raw_data)print(img_data.eval())#使用pyplot工具可视化得到的图像plt.imshow(img_data.eval())#plt.show()#将数据的类型转化为实数,方便下面的程序进行处理img_data=tf.image.convert_image_dtype(img_data,dtype=tf.float32)#通过tf.image.resize_images函数调整图像的大小,method是调整的算法,0:双线性差值 1:最近邻居法 2:双3次差值法 3:面积差值法resized=tf.image.resize_images(img_data,[300,300],method=0) #输出图像的大小print(resized.get_shape())plt.imshow(resized.eval())#plt.show()#将表示一张图片的三维矩阵重新按照jpeg的格式编码存入文件中encode_image=tf.image.encode_jpeg(img_data)with tf.gfile.GFile('./path/to/picture/timg_output.jpg','wb') as f:f.write(encode_image.eval())#截取部分图像,从中间截取,如果截取的面积大于原图像,则填充0croped=tf.image.resize_image_with_crop_or_pad(img_data,1000,1000)plt.imshow(croped.eval())plt.show()#按照比例裁剪图像central_croped=tf.image.central_crop(img_data,0.5)plt.imshow(central_croped.eval())plt.show()#图像翻转#将图像上下翻转flipped=tf.image.flip_up_down(img_data) #将图像左右翻转flipped=tf.image.random_flip_left_right(img_data)#将图像沿对角线翻转transposed=tf.image.transpose_image(img_data)#将图像随机进行翻转flipped=tf.image.random_flip_left_right(img_data)flipped=tf.image.random_flip_up_down(img_data) #随机进行上下翻转#图像的色彩调整#调整图像的亮度、对比度、饱和度和色相#将图像的亮度-0.5adjusted=tf.image.adjust_brightness(img_data,-0.5)#在[-max_delta,max_delta]内随机调整图像的亮度adjusted=tf.image.random_brightness(img_data,0.5)#图像的对比度-5adjusted=tf.image.adjust_contrast(img_data,-5)#在[lower,upper]范围内随机调整图的对比度adjusted=tf.image.random_contrast(img_data,2,7)#调整图像的色相adjusted=tf.image.adjust_hue(img_data,0.3)#在[-maxdelta,maxdelta]范围内随机调整图像的色相 maxdelat 在0-0.5的范围内adjusted=tf.image.random_hue(img_data,0.4) #调整图像的饱和度adjusted=tf.image.adjust_saturation(img_data,5) #在[lower,upper]范围内随机调整图像的饱和度adjusted=tf.image.random_saturation(img_data,1,10)#tensorflow还提供了图像的准净化过程,将图像的数字均值变为0,方差变为1adjusted=tf.image.per_image_standardization(img_data)#许多的图像需要关注的物体可以使用标注框标注出来#tf.image.draw_bounding_boxes函数要求处理图像的矩阵是实数,输入是一个batch数据,多张图像组成的四维矩阵,所以需要将解码后的图像增加一个维度batched=tf.expand_dims(img_data,0) #下面都是相对的位置boxes=tf.constant([[[0.05,0.05,0.7,0.9],[0.2,0.3,0.9,0.8]]])result=tf.image.draw_bounding_boxes(batched,boxes)plt.imshow(result[0].eval())plt.show()
这篇关于Tensorflow图像处理相关操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!