视频帧预处理遇TypeError:'int'对象不可迭代,求开发者协助
问题分析与修复方案
错误根源
报错TypeError: 'int' object is not iterable出现在for images in onlyfiles[img]:这一行,说明onlyfiles[img]是整数类型,不是可迭代的列表/集合,没法用for循环遍历。结合你的代码和调用情况,主要问题有这几个:
- 扩展名参数传错了:调用时传了
.Fit,这根本不是合法的图片格式,会导致ReadFileNames返回的onlyfiles结构完全不符合预期(大概率返回的是文件数量而非路径列表)。 - 循环逻辑乱套:
- 外层用
img当索引,内层又重复遍历onlyfiles[img],但如果onlyfiles存的是单个文件路径(不是嵌套列表),自然会触发类型错误。 - 代码里直接用了
dirs[i]和file_names[i][count],但i根本没定义,这后续还会报新错。 - 你对着整数类型的
img执行split('/'),img是循环的索引数字,不是文件路径字符串,肯定不对。
- 外层用
- 列表初始化冗余:
img_list初始塞了[1,2,3,4],最终返回的列表会带这些无关值,应该初始化成空列表。
修复后的代码
from typing import List, Union from tqdm import tqdm def Fit_Preprocessing(path: str, frames_ext: str) -> List: if frames_ext is None or not frames_ext.startswith('.'): raise TypeError( 'Invalid Value for argument `frames_ext`, it cannot be None. Give proper extensions of the frames e.g: `.tif` or `.png` etc!') print('\n\nProcessing Images in this Dataset Path: {0}\n'.format(path)) # 先确认ReadFileNames返回的是文件路径列表、对应文件名列表、目录列表 onlyfiles, file_names, dirs = ReadFileNames(path, frames_ext) img_list = [] # 初始化空列表,避免混入无关初始值 for idx in tqdm(range(len(onlyfiles))): img_path = onlyfiles[idx] # 拆分文件路径(这里假设用的是Unix风格路径,Windows路径可换成split('\\')) # 修正变量引用:用当前循环索引idx替代未定义的i img_name = dirs[idx] + '_' + file_names[idx] write_path = 'ProcessedImages/' + path.split('/')[1] gray = ProcessImg(img_name, read_path=img_path, write=True, write_path=write_path, res_shape=(227, 227)) img_list.append(gray) return img_list # 调用时务必传正确的图片扩展名,比如'.tif'或'.png' img_list = Fit_Preprocessing(path, frames_ext='.tif')
额外要注意的点
- 先打印
onlyfiles、file_names、dirs的类型和内容,确认ReadFileNames的返回结构符合预期——onlyfiles得是存文件路径的列表,不能是整数或其他非迭代类型。 - 如果
onlyfiles是嵌套列表(每个元素对应一个文件夹的文件列表),再调整循环逻辑:外层遍历文件夹,内层遍历每个文件夹里的文件。 - 检查
ProcessImg函数的参数要求,确保read_path传的是合法的文件路径字符串。
内容的提问来源于stack exchange,提问作者Stephen Longwe
相关产品推荐
相关产品推荐

