欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【python】读取图片复制并重命名

程序员文章站 2022-07-13 09:00:12
...

```python
# -*- coding:utf8 -*-
import os
import argparse
import shutil
# imgpath = './img'
# new_imgpath = './new_img'
# jsonpath = './gt'
# new_jsonpath = './new_json'

# j = 0  #文件名起始
# for root, dirs, files in os.walk(imgpath):
#     for i in range(len(files)):
#         json_file = files[i].split('.')[0]
#         shutil.copy(os.path.join(imgpath,files[i]), os.path.join(new_imgpath, str(j).zfill(12) + '.jpg'))
#         shutil.copy(os.path.join(jsonpath,json_file + '.json'), os.path.join(new_jsonpath, str(j).zfill(12) + '.json'))
#         j += 1

# print ('this work has done')

parser = argparse.ArgumentParser()
parser.add_argument('--timestamp_file', type=str, default='timestamp.txt')
parser.add_argument('--image_file', type=str, default='image.txt')
parser.add_argument('--image_path', type=str, default='image')
opt = parser.parse_args()

def rename_img(time_stamp, filelist, img_path):
    #filelist = os.listdir(img_path) #获取文件路径
    total_num = len(filelist) #获取文件长度(个数)
    i = 0 #表示文件的命名是从1开始的
    for i in range(total_num):
        item = filelist[i]    # 迭代 3 次
        for n in range(3):
            if i*3 + n == len(time_stamp):
                break
            item_timestamp =  time_stamp[i*3 + n]
            n = n + 1
            shutil.copy(os.path.join(item), os.path.join(img_path, item_timestamp + '.jpg'))
            # if item.endswith('.jpg'): #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
            #     src = os.path.join(os.path.abspath(img_path), item)
            #     dst = os.path.join(os.path.abspath(img_path), item_timestamp + '.jpg')#处理后的格式也为jpg格式的,当然这里可以改成png格式
            #     try:
            #      os.rename(src, dst)
            #      print ('converting %s to %s ...' % (src, dst))
            #     except:
            #      continue

    print ('total %d to rename & converted %d jpgs' % (total_num*3, i))
    
if __name__ == '__main__':
    classes_path = os.path.expanduser(opt.timestamp_file)
    with open(classes_path, mode='r') as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]

    images_path = os.path.expanduser(opt.image_file)
    with open(images_path, mode='r') as f:
        images_names = f.readlines()
    images_names = [c.strip() for c in images_names]
    rename_img(class_names, images_names, opt.image_path)


相关标签: python python