使用rembg与PIL实现Python图像背景移除时遇模块错误求助
问题排查与解决
问题描述
基于rembg与PIL编写的图像背景移除程序运行报错,代码如下:
from rembg import remove from PIL import Image input_path = 'ballroom1.jpg' output_path = 'output.png' input = Image.open(input_path) output = remove(input) output.save(output_path)
报错信息
Traceback (most recent call last): File "D:\PyCharm\BackgroundRemover\Remove.py", line 1, in <module> from rembg import remove File "D:\PyCharm\Python\rembg\__init__.py", line 5, in <module> from .bg import remove File "D:\PyCharm\Python\rembg\bg.py", line 5, in <module> import numpy as np File "D:\PyCharm\Python\numpy\__init__.py", line 124, in <module> from numpy.__config__ import show as show_config File "D:\PyCharm\Python\numpy\__config__.py", line 12, in <module> os.add_dll_directory(extra_dll_dir) AttributeError: module 'os' has no attribute 'add_dll_directory'
当前环境:numpy 1.23.5、rembg 2.0.30,已重装两个模块但问题未解决。
原因分析
os.add_dll_directory()是Python 3.8及以上版本才新增的系统方法,你使用的Python版本低于3.8。而numpy 1.23.5的最低兼容Python版本为3.8,低版本Python无法识别该方法,导致导入numpy时触发报错。
解决步骤
方案1:升级Python版本(推荐)
- 下载并安装Python 3.8或更高版本(如3.9、3.10)
- 重新安装numpy和rembg:
pip install --upgrade numpy rembg - 运行原代码即可正常执行。
方案2:降级numpy到兼容低版本Python的版本
如果无法升级Python,根据你的Python版本选择对应numpy版本:
- 若使用Python 3.7:安装numpy 1.21.x版本(numpy 1.22及以上要求Python 3.8+)
pip install numpy==1.21.6 - 若使用Python 3.6:安装numpy 1.19.x版本
pip install numpy==1.19.5 - 降级后验证rembg是否兼容,若出现依赖错误,可同步降级rembg到适配版本,例如:
pip install rembg==1.0.27
内容的提问来源于stack exchange,提问作者Massapequa
相关产品推荐
相关产品推荐

