Python-opencv批量处理文件夹中图像操作
1. 递归遍历多层文件夹,获取所有图像文件的路径:
python
import os
from pathlib import Path
def get_image_paths(root_dir, extensions=None):
"""
递归获取指定文件夹下所有图像文件的路径
参数:
root_dir (str): 根文件夹路径
extensions (list): 图像扩展名列表,默认为常见图像格式
返回:
list: 图像文件的完整路径列表
"""
if extensions is None:
extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
# 统一转换为小写,方便比较
extensions = [ext.lower() for ext in extensions]
image_paths = []
root_path = Path(root_dir)
if not root_path.exists():
raise FileNotFoundError(f"路径不存在: {root_dir}")
# 使用rglob递归遍历所有文件
for file_path in root_path.rglob('*'):
if file_path.is_file() and file_path.suffix.lower() in extensions:
image_paths.append(str(file_path))
return image_paths
# 使用示例
if __name__ == "__main__":
# 示例1:使用默认扩展名
root_directory = "./images" # 替换为您的文件夹路径
try:
paths = get_image_paths(root_directory)
print(f"找到 {len(paths)} 张图像")
for path in paths[:5]: # 只打印前5个
print(path)
except FileNotFoundError as e:
print(e)
# 示例2:自定义扩展名
custom_extensions = ['.jpg', '.png']
paths_custom = get_image_paths(root_directory, custom_extensions)
print(f"\n仅jpg和png格式: {len(paths_custom)} 张")