Skip to main content
 首页 » 编程设计

python之如何通过 Python 中子文件夹中的图像文件目录迭代图像处理

2025年05月04日9zhwl

在如何连接迭代列表(声明为 fileListL)方面需要特别帮助,该列表是根据子目录(左)中的一系列图像文件动态构建的,并循环直到到达帧范围的末尾。所有脚本都按预期在单个帧上工作,但我无法让它循环遍历多个帧。想法、想法?

# this module runs within a root directory that contains one sub folder named 'left' and 15 sub folders expressed in the dirL as ('left/01','left/02, . . . .) 
# each folder can have any number of sequential .jpg images in the format 'name.0000.jpg' 
 
import os 
import sys 
import glob 
import Image 
from itertools import izip, count 
 
# create Master List of files in Left Directories along with a count of files 
 
global fileListL 
fileListL = [] 
for root, dirs, files in os.walk(r'left/'): 
    for file in files: 
        if file.endswith('.jpg'): 
                fileListL.append('left/'+file) 
print fileListL 
 
# Iterator 
global inFrame 
global outFrame 
inFrame = 'left/test.0000.jpg' # testing temp needs dynamic variable, trying to use fileList L list to dynamically increment thru frames 
outFrame = inFrame[5:-5] 
crops = ((0, 0, 1920, 1080),(1920, 0, 3840, 1080), (3840, 0, 5760, 1080), (5760, 0, 7680, 1080), (7680, 0, 9600, 1080), (9600, 0, 11520, 1080), (11520, 0, 13440, 1080), (13440, 0, 15360, 1080), (15360, 0, 17280, 1080), (17280, 0, 19200, 1080), (19200, 0, 21120, 1080), (21120, 0, 23040, 1080), (23040, 0, 24960, 1080), (24960, 0, 26880, 1080), (26880, 0, 28800, 1080)) 
quads = ('01_', '02_', '03_', '04_', '05_', '06_', '07_', '08_', '09_', '10_', '11_', '12_', '13_', '14_', '15_') 
dirL= ('left/01/', 'left/02/', 'left/03/', 'left/04/', 'left/05/', 'left/06/', 'left/07/', 'left/08/', 'left/09/', 'left/10/', 'left/11/', 'left/12/', 'left/13/', 'left/14/', 'left/15/') 
 
for i in fileListL: 
    for infile in glob.glob( os.path.join(inFrame) ): 
        print "current file is: " + infile 
        oL = Image.open(inFrame) # needs dynamic variable for frames 
        for i, each_quad, each_frame, each_dirL in izip(count(), crops, quads, dirL): 
            print i, each_quad, each_frame, each_dirL 
            frame = oL.crop(((each_quad))) 
            frame.save((each_dirL)+(each_frame)+(outFrame)+'.png') 

请您参考如下方法:

您的代码中有太多“复制粘贴”错误,难以理解其目的。

  • 使用相同名称的 for 循环变量 (i) 嵌套 for 循环。
  • os.path.join(inFrame) 期望包含路径组件的列表,inFrame 似乎是一个字符串
  • 第一个 for 循环的目的是什么(for i in fileListL),似乎您正在丢弃 i。
  • 等等...

请使用您的文件树布局和适用于单个文件的步骤更新问题,也许我们可以帮助您。

[更新]

似乎您的代码可以简化为:

for i, file_name in enumerate(glob.glob('left/*.jpg')): 
    out_frame = 'left/%02d/%s.png' % (i+1, file_name[5:-5]) 
    print "current input file is: '%s', output file is: %s" % (file_name, out_frame) 
    img = Image.open(file_name) 
    for i, crop in enumerate(crops): 
        frame = img.crop(crop) 
        frame.save(out_frame) 

这是未经测试的代码,只是为了给您指明正确的方向。