1. 程式人生 > 其它 >python 對資料夾下的所有圖片進行重新命名

python 對資料夾下的所有圖片進行重新命名

技術標籤:深度學習深度學習python影象處理

在做深度學習的相關專案時,經常需要對圖片資料集進行重新命名。這裡通過python實現遍歷資料夾圖片並重命名,並提供了完整程式碼,大家可以根據自己的需求靈活修改。

1.需求

把資料夾下的每張圖片重新命名為 :疫苗名稱 + 固定長度的編碼。如:卡介苗_1.jpg 重名為 卡介苗_00001.jpg

2.程式碼

import os
# 圖片所在路徑
root_path = "E:\\images\\卡介苗"
filename_list = os.listdir(root_path)
for filename in filename_list:
    if filename.endswith('.jpg'):
        src_img_path = os.path.join(os.path.abspath(root_path), filename)
        new_img_code = filename.split('_')[1].split('.')[0].zfill(5)

        dst_img_path = os.path.join(os.path.abspath(root_path), filename.split('_')[0] + '_' + new_img_code + '.jpg')
        try:
            os.rename(src_img_path, dst_img_path)
            print('converting %s to %s ...' % (src_img_path, dst_img_path))
        except:
            continue

執行結果: