基于tensorflow实现数据增强
import tensorflow as tf
import os
import random
source_file="./Data aug/picture/" #原始文件地址
target_file="./aug_pic/" #修改后的文件地址
num=50 #产生图片次数
if not os.path.exists(target_file): #如果不存在target_file,则创造一个
os.makedirs(target_file)
file_list=os.listdir(source_file) #获得该目录下的所有的文件和文件夹的名字,存放于一个列表中
with tf.Session() as sess:
for i in range(num):
max_random=len(file_list)-1
a = random.randint(0, max_random)
#随机数字区间
# tf.gfile.FaterGFile(source, decodestyle)
# 第一个参数是图片的路径,第二个参数是编解码的方式,'r'为utf8编码,'rb'为非utf8编码
# rb不是特别明白
image_raw_data=tf.gfile.FastGFile(source_file+file_list[a],"rb").read()#读取图片
print("正在处理:",file_list[a])
# 解码后结果为张量
image_data=tf.image.decode_jpeg(image_raw_data)
filpped_le_re=tf.image.random_flip_left_right(image_data) #随机左右翻转
filpped_up_down=tf.image.random_flip_up_down(image_data) #随机上下翻转
adjust=tf.image.random_brightness(filpped_up_down,0.4) #随机调整亮度
# 转换图像的数据格式
image_data=tf.image.convert_image_dtype(adjust,dtype=tf.uint8)
# 编码
encode_data=tf.image.encode_jpeg(image_data)
# 存入到target_file中
# with tf.gfile.GFile(target_file+str(i)+"_enhance"+".jpeg","wb") as f:
# f.write(encode_data.eval())
print("图像增强完毕")
附:tensorflow实现图像的读写
import matplotlib.pyplot as plt
import tensorflow as tf
# 读取图像数据
img = tf.gfile.FastGFile('./assignment01/dog.png', 'rb').read()
with tf.Session() as sess:
# 用ipeg格式将图像解码得到三维矩阵(png格式用decode_png, jpg格式用jpeg)
# 解码后得到结果为张量
img_data = tf.image.decode_png(img)
# 打印出得到的三维矩阵
print(img_data.eval())
# 使用pyplot可视化得到的图像
plt.imshow(img_data.eval())
plt.show()
#转换格式
# 转换图像的数据类型,应该就是转换为标准格式,没有什么特殊的作用
img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8)
# 将图像的三维矩阵重新按照png格式存入文件
encoded_image = tf.image.encode_png(img_data)
# 得到图像的png格式
with tf.gfile.GFile('./assignment01/model.png', 'wb') as f:
f.write(encoded_image.eval())