写一个遍历文件夹内所有图像的函数,用tensorflow打开图像,crop成batch后在存到本地disk;
过程中随着打开图像的增加,代码的运行速度会越来越慢;
用内存管理工具看到物理内存会逐渐增加;
Debug了一下,应该是代码在decode图像之后并没有释放掉图像内存导致的;
在with外添加“tf.reset_default_graph()”即可解决;
实例代码如下(最后一行可以完成内存的释放,解决打开图像越多运行速度越慢的问题):
def get_imgpair(file_list): counter = 0 for files in file_list: img_raw_data = tf.gfile.FastGFile(files, 'rb').read() with tf.Session() as sess: img_data = tf.image.decode_png(img_raw_data) for ln in range(0, DATA_HEIGHT, 100): for px in range(0, DATA_WIDTH, 100): if ln+BATCH_HEIGHT >= DATA_HEIGHT or px+BATCH_WIDTH >= DATA_WIDTH: continue else: counter = counter + 1 img_crop = tf.image.crop_to_bounding_box(img_data, ln, px, BATCH_HEIGHT, BATCH_WIDTH) img_sv = tf.image.encode_png(img_crop) with tf.gfile.GFile(train_batch_path+'src/'+str(counter), 'wb') as f: f.write(img_sv.eval()) tf.reset_default_graph() # release pic memory