You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python multiprocessing处理图片瓦片pool.map报FileNotFoundError求助

问题根因

你遇到的字符串被拆分报错的直接原因是multiprocessing.Pool.map的用法错误:
pool.map(func, iterable)要求第二个参数是可迭代对象,执行逻辑是把可迭代对象里的每一个元素逐个传给func运行。你当前的代码遍历onlytiles列表,每次把单个字符串路径作为参数传给pool.map,而字符串本身属于可迭代对象,会被自动拆成单个字符逐个传入semi_func,第一个字符就是t,因此触发了找不到文件t的报错。

同时你的代码还存在一个隐含问题:多进程的地址空间是相互隔离的,子进程中修改的ans_tiles字典不会同步到主进程,主进程最终拿到的ans_tiles会永远是空字典。


修复后代码

1. 修改处理函数semi_func

取消子进程内对全局字典的操作,直接返回当前处理的路径和对应结果即可:

def semi_func(tile):
    with open(tile, 'rb') as f:
        img = Image.open(BytesIO(f.read()))
        resized_im, seg_map = MODEL.run(img)
        vis_segmentation_tiles(str(tile), resized_im, seg_map)
        x = np.unique(seg_map).tolist()
        print("THIS IS X", x)
        # 直接返回当前路径和处理结果,不操作全局字典
        return tile, x

2. 修改多进程调用逻辑

去掉冗余的循环调用,直接把完整的路径列表传给pool.map,最后用返回结果拼装字典:

def split_tiles_new(image_path, tiledir):
    print("1")
    pool = Pool(processes=5)
    print("2")
    num_tiles = 9
    tiles = image_slicer.slice(image_path, num_tiles, save=False)
    print("3")
    print(tiles)
    image_slicer.save_tiles(tiles, directory=tiledir)
    print(tiles)
    print("TILES ABOEVE")
    
    onlytiles = [os.path.join(tiledir,f) for f in listdir(tiledir) if isfile(join(tiledir, f))]
    ans_tiles = {}
    print(onlytiles)
    onlytiles = list(map(str, onlytiles))
    for t in onlytiles:
        print(t)
    # 移除原有循环,直接传入完整路径列表
    results = pool.map(semi_func, onlytiles)
    pool.close()
    pool.join()
    # 用返回结果拼装字典
    ans_tiles = dict(results)
    print(ans_tiles)
    return ans_tiles

内容的提问来源于stack exchange,提问作者mike0494

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:15:00