遍历文件夹以及子文件夹的图片,利用opencv改变大小并保存至一个文件夹

遍历文件夹以及子文件夹的图片,利用opencv改变大小并保存直一个文件夹

代码实现功能如题意,代码如下:

import os,cv2
from tkinter import image_names

nameList = []
def listDir(dirTemp):
    if None == dirTemp:
        return
    global nameList
    if not os.path.exists(dirTemp):
        print("file or directory isn't exist")
        return
    if os.path.isfile(dirTemp):
        if dirTemp.find('.jpg') > 0: nameList.append(dirTemp)  #查找后缀名含有bmp的文件并将其名称路径加入到列表当中去
        return
    resultList = os.listdir(dirTemp)   #os.listdir()方法用于返回指定文件夹包含的文件或文件夹的名字的列表
    for fileOrDir in resultList:
        listDir(dirTemp + "/" + fileOrDir)  #递归调用,搜查子文件夹下的文件
    return nameList


def resize_img(nameList,new_path):
    
    for str_ in nameList:
        img_name = str_.split("/")[-1]
        path = str_
        print(path)
        image = cv2.imread(path,0)
        img = cv2.resize(image,(640,640))

        image_store = new_path + '\\' + 'image' +'/'+ img_name  #image为新文件夹
        print(img_name)
        cv2.imwrite(image_store,img)
    

if __name__ == "__main__":
    orignal_path = "D:\BJ_data" #原始路径
    new_path = "D:\BJ_data" #新路径
    nameList = listDir(orignal_path)
    resize_img(nameList,orignal_path,new_path)

    

你可能感兴趣的:(python,openCV,opencv,python,计算机视觉)