python遍历多层次文件夹并修改图像

参考:https://www.jianshu.com/p/433bfe17df08

import os
from PIL import Image
#采用递归遍历的方式遍历图片
def recurve_opt(root_1, root_2):
    if not os.path.exists(root_2):
        os.makedirs(root_2)
    for file in os.listdir(root_1):
        source_file = os.path.join(root_1, file)
        target_file = os.path.join(root_2, file)
        if os.path.isfile(source_file):
            (path, extension) = os.path.splitext(source_file)
            if extension == '.png':
                source_img=Image.open(source_file)
                if "ground_truth" in path:
                    gray_img=source_img
                else:
                    gray_img=source_img.convert("L")
                gray_img.save(target_file)
        else:
            recurve_opt(source_file, target_file)
def main():
    imgRoot="MyData"
    imgRootGray="MyDataGray"
    recurve_opt(imgRoot, imgRootGray)
if __name__ == '__main__':
    main()

 

import os
import cv2
#采用递归遍历的方式遍历图片
def recurve_opt(root_1, root_2):
    if not os.path.exists(root_2):
        os.makedirs(root_2)
    for file in os.listdir(root_1):
        source_file = os.path.join(root_1, file)
        target_file = os.path.join(root_2, file)
        if os.path.isfile(source_file):
            (path, extension) = os.path.splitext(source_file)
            if extension == '.png':
                source_img=cv2.imread(source_file)
                source_img=cv2.resize(source_img,(512,512),interpolation=cv2.INTER_CUBIC)
                gray_img=cv2.cvtColor(source_img,cv2.COLOR_RGB2GRAY)
                cv2.imwrite(target_file,gray_img)
        else:
            recurve_opt(source_file, target_file)
def main():
    imgRoot="MyData"
    imgRootGray="MyDataGray"
    recurve_opt(imgRoot, imgRootGray)
if __name__ == '__main__':
    main()

注意,以上代码尽管形式上改为了单通道图像,但是读入的时候可能还会受读入函数的影响,例如opencv的imread默认就是以3通道图像读入,这时候需要指定imread(...,-1)这个参数才是以单通道的形式读入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值