一、前言
经过短暂的认知实习学期的学习,笔者得到一个需求,那就是需要把一系列图片整合在一起形成一个高通道的图片,然后以一个二维数组的形式进行保存,这里的技术要求其实不是很难,但是对于细节的处理和把握还是相对比较高的,下面做一下简要的介绍。
二、数据集介绍
首先这个是一个8分类的数据集,每个分类在单独的一个文件夹下面,每一个文件夹下面还有若干个子文件夹,每个子文件夹下面存放的是若干后缀名为.jpg图片序列。
三、执行步骤(思路整理)
1.使用交互式的形式创建会话
sess=tf.InteractiveSession()
2.遍历数据集中所有文件夹(类别文件夹)
image_set_list=os.listdir(FOLDERNAME)
os.chdir(FOLDERNAME)
for folder in image_set_list:
其中os.chdir 为os的一个方法,用于定位文件作用域信息。
3.遍历每一个folder的子目录(图片文件夹)
num_a_list=os.listdir(folder)
#遍历folder下面的所有目录
os.chdir(folder+'/'+num_a_list[0]+'/')
for num in num_a_list:
这里的os.chdir用于定位,辅助循环遍历
4.图片变换解码及通道数叠加
#这里规格化的每张图片尺寸为108×108=11664
#temp_variable为初始叠加值
temp_variable=np.zeros((11664,0))
for i in range(len(os.listdir('./'))):
#循环进入图片子目录
#读取每张图片的信息
file_contents=tf.read_file('%d.jpg'%i)
对图片进行相应格式的解码
image_tensor=tf.image.decode_jpeg(file_contents,channels=1)
#对图片进行相应的切除
crop_to_bounding_box = tf.image.crop_to_bounding_box(image_tensor, offset_width=170, offset_height=0,
target_width=450, target_height=432)
#对图片进行resize
image_tensor = tf.image.resize_images(images=crop_to_bounding_box, size=(108, 108),
method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
#将图片变换为二维数组
image_tensor=tf.reshape(image_tensor,shape=(11664,1))
#将tensor对象转化为np.array对象
image_np=image_tensor.eval(session=sess)
#叠加
out_np=np.c_[temp_variable,image_np]
temp_variable=out_np
#打印
print(temp_variable)
5.数据保存
for i in range(25-len(os.listdir('./'))):
zeros_np=np.zeros((11664,1))
out_np=np.c_[temp_variable,zeros_np]
temp_variable=out_np
np.savetxt('../array%d-25-%s.txt'%(len(os.listdir('./')),num[4:]),temp_variable)
os.remove("../num")
四、数据集提取
os.chdir("image_set/")
list_y=[1,2,3,4,5,6,7,8]
list_x=['a','b','c','d','e','f','g','h']
os.chdir(list_x[0])
out_y=[]
out_x=[]
for i in range(len(list_x)):
os.chdir('../'+list_x[i]+'/')
for item in os.listdir('./'):
train_img=np.loadtxt(item)
out_y.append(list_y[i])
out_x.append(train_img)
print(train_img)
print(out_y)
#提取到的训练集
train_img=out_x
train_label=out_y
print(len(train_img))
print(len(train_label))
五、小结
到这里数据的提取整合就大致完成了,但是还是有一些不足的地方需要改进与修正,并且通过这次的整理,熟悉了os的操作和tensorflow中的图片的转换函数。下一步就是使用简单的CNN网络结构使用这个十分微小的训练集训练出一个MINI的模型。后面的文章将会写明。