OpenCV遍历图像

1、os.walk
函数原型

def walk(top, topdown=True, onerror=None, followlinks=False)
#top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
  # root 表示当前正在访问的文件夹路径
  # dirs 表示该文件夹下的子目录名list(该文件夹下的文件夹)
  # files 表示该文件夹下的文件list

#topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
#下面两个参数不用管
#onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
#followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。

遍历文件使用方法

def walkFile(file):
    for root, dirs, files in os.walk(file):
    # 遍历文件
        for f in files:
            print(os.path.join(root, f))
        # 遍历所有的文件夹
        for d in dirs:
            print(os.path.join(root, d))

遍历图像使用方法,在使用过程中,尽量保证只在你要访问的根目录下有图像文件,不容易出问题

import os
from PIL import Image 
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
        image=Image.open(os.path.join(root, name))
        image.show('your_title')
        image.save('image_file_name')

2 os.listdir
os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。

dirs = os.listdir( path )
# 输出所有文件和文件夹
for file in dirs:
   print (file)
   #这个位置也可以加上文家后缀判断,判断是否为图像
   image=Image.open(os.path.join(path, file))

版权声明:本文为m0_37737957原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。