1. 前言
最近在家学习深度学习的caffe,在做某类识别的时候,自己采集到的图片,命名方式很乱,不利于caffe的模型训练, 所以采用python来实现对图片或者文本数据的批量重命名。
2. 基本思路
调用到python 的os 模块, 对某文件夹下的数据进行遍历(listdir), 同时使用 rename 进行重命名操作即可
3. 实现效果
4. 实现代码
代码如下
# -*- coding:utf8 -*-
#usage:实现对图片的批量重命名
#author:Zoutao
#time:2018/2/22
import os
class BatchRename():
#定义函数执行图片的路径
def __init__(self):
self.path = '/home/nvidia/caffe/data/cheb/test/aodi'
#定义函数实现重命名操作
def rename(self):
filelist = os.listdir(self.path)
total_num = len(filelist)
i = 101
for item in filelist:
if item.endswith('.jpg'):
src = os.path.join(os.path.abspath(self.path), item)
dst = os.path.join(os.path.abspath(self.path), str(i) + '.jpg')
try:
os.rename(src, dst)
print 'converting %s to %s ...' % (src, dst)
i = i + 1
except:
continue
print ('total %d to rename & converted %d jpgs' % (total_num, i))
#主函数调用
if __name__ == '__main__':
demo = BatchRename()
demo.rename()
You got a dream, you gotta protect it.
如果你有梦想的话,就要去捍卫它 。 ——《当幸福来敲门》