python - 查找包含图像的子文件夹

标签 python optimization python-os

获取包含文件的子文件夹路径的最有效方法是什么。例如,如果这是我的输入结构。

inputFolder    
│
└───subFolder1
│   │
│   └───subfolder11
│       │   file1.jpg
│       │   file2.jpg
│       │   ...
│   
└───folder2
    │   file021.jpg
    │   file022.jpg

如果我通过getFolders(inputPath), 它应该将输出作为包含图像的文件夹列表返回 ['inputFolder/subFolder1/subFolder11','inputFolder/folder2']

目前我正在使用我的库 TreeHandler ,它只是 os.walk 的包装器,用于获取所有文件。

import os
from treeHandler import treeHandler
th=treeHandler()
tempImageList=th.getFiles(path,['jpg'])
### basically tempImageList will be list of path of all files with '.jpg' extension

### now is the filtering part,the line which requires optimisation.
subFolderList=list(set(list(map(lambda x:os.path.join(*x.split('/')[:-1]),tempImageList))))

我认为可以更有效地完成。

提前致谢

最佳答案

  • 分割路径的所有部分并重新连接它们似乎会降低效率。
  • 查找“/”最后一个实例的索引并进行切片的速度要快得多。

    def remove_tail(path):
        index = path.rfind('/') # returns index of last appearance of '/' or -1 if not present
        return (path[:index] if index != -1  else '.') # return . for parent directory
    .
    .
    .
    subFolderList = list(set([remove_tail(path) for path in tempImageList]))
    
  • 已在 AWA2 数据集文件夹(50 个文件夹和 37,322 个图像)上进行验证。

  • 观察到的结果快了约 3 倍。
  • 使用列表理解增强了可读性。
  • 处理了父目录包含图像的情况(这会导致现有实现出现错误)

添加用于验证的代码

import os
from treeHandler import treeHandler
import time

def remove_tail(path):
    index = path.rfind('/')
    return (path[:index] if index != -1  else '.')

th=treeHandler()
tempImageList= th.getFiles('JPEGImages',['jpg'])
tempImageList = tempImageList
### basically tempImageList will be list of path of all files with '.jpg' extension

### now is the filtering part,the line which requires optimisation.
print(len(tempImageList))
start = time.time()
originalSubFolderList=list(set(list(map(lambda x:os.path.join(*x.split('/')[:-1]),tempImageList))))
print("Current method takes", time.time() - start)

start = time.time()
newSubFolderList = list(set([remove_tail(path) for path in tempImageList]))
print("New method takes", time.time() - start)

print("Is outputs matching: ", originalSubFolderList == newSubFolderList)

关于python - 查找包含图像的子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207834/

相关文章:

python - 为什么我会得到 "TypeError: open() missing required argument ' 标志' (pos 2 )"or "TypeError : an integer is required (got type str)"when opening a file?

python - 对整个复数数组进行插值

python - 通过 Python 连接远程 MySQL

python - python 中 os.rename 的中断

c++ - c/c++ 优化调用函数中的常量变量

sql-server - SQL Server 性能 : Non-clustered Index + INCLUDE columns vs. 聚集索引 - 等效吗?

python - jupyter笔记本可以找到自己的文件名吗?

python - Google TaskQueue(拉)通过 API 插入任务

python - 在没有 numpy 的情况下制作多维数组的好方法

java - 执行操作的最佳时间 : within, 或循环后