1. 程式人生 > 其它 >Python常用程式碼功能

Python常用程式碼功能

Python常用程式碼功能

提取一個資料夾下的所有圖片(含子目錄)到另一個資料夾下

import os
import cv2
import shutil

def getFileList(dir,Filelist, ext=None):
    """
    獲取資料夾及其子資料夾中檔案列表
    輸入 dir:資料夾根目錄
    輸入 ext: 副檔名
    返回: 檔案路徑列表
    """
    newDir = dir
    if os.path.isfile(dir):
        if ext is None:
            Filelist.append(dir)
        else:
            if ext in dir[-3:]:
                Filelist.append(dir)
    
    elif os.path.isdir(dir):
        for s in os.listdir(dir):
            newDir=os.path.join(dir,s)
            getFileList(newDir, Filelist, ext)
 
    return Filelist
 
org_img_folder=r'E:\documnets\Machine-Learning-Notes'
new_img_folder=r'E:\documnets\Machine-Learning-Note'
# 檢索檔案
imglist = getFileList(org_img_folder, [], 'jpg')
print('本次執行檢索到 '+str(len(imglist))+' 張影象\n')
 
for imgpath in imglist:
    imgname= os.path.splitext(os.path.basename(imgpath))[0]
    new_path = os.path.join(new_img_folder,imgname)+'.jpg'
    shutil.copy(imgpath,new_path)
    print(imgpath)
    #img = cv2.imread(imgpath, cv2.IMREAD_COLOR)
    # 對每幅影象執行相關操作