配置一整天,踩了一些坑。现运行成功,与大家分享
环境:win10
VS2019
python 3.8
pytorch 1.7.0
CUDA 11.0
源码下载地址:https://github.com/NVlabs/SegFormer?tab=readme-ov-file
CUDA下载地址:https://developer.nvidia.com/cuda-11-0-1-download-archive
conda create -n seg python=3.8
conda activate seg
pip install torch==1.7.0+cu110 torchvision==0.8.1+cu110 torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
pip install mmcv-full==1.3.0 -f https://download.openmmlab.com/mmcv/dist/cu110/torch1.7.0/index.html
pip install opencv-python==4.5.1.48
pip install IPython
pip install timm
切换到segformer-master目录:
cd segformer-master
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -e . --user
image_demo.py如下,需手动修改文件路径,直接在pycharm点运行
import os
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from mmseg.apis import inference_segmentor, init_segmentor
from mmseg.core.evaluation import get_palette
import mmcv
# 设置环境变量以允许重复的OpenMP运行时(临时解决方案)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
def show_result_pyplot(model, img, result, palette=None, fig_size=(15, 10), out_file=None):
if hasattr(model, 'module'):
model = model.module
# 将结果图像保存到out_file
model.show_result(img, result, palette=palette, show=False, out_file=out_file)
# 加载保存的图像以显示
if out_file:
img = mmcv.imread(out_file)
if img is None:
raise ValueError(f"从{out_file}加载输出图像失败")
plt.figure(figsize=fig_size)
plt.imshow(mmcv.bgr2rgb(img))
plt.show()
else:
raise ValueError("未指定输出文件路径")
def main():
parser = ArgumentParser()
parser.add_argument('-img', help='图像文件', default=r'D:\PyCharmproject\SegFormer-master\demo\demo1.png')
parser.add_argument('-config', help='配置文件',
default=r'D:\PyCharmproject\SegFormer-master\local_configs\segformer\B0\segformer.b0.1024x1024.city.160k.py')
parser.add_argument('-checkpoint', help='检查点文件',
default=r'D:\PyCharmproject\SegFormer-master\checkpoint\segformer.b0.1024x1024.city.160k.pth')
parser.add_argument('--out-file', default='./output.png', help='输出文件路径')
parser.add_argument(
'--device', default='cuda:0', help='用于推断的设备')
parser.add_argument(
'--palette',
default='cityscapes',
help='用于分割图的颜色调色板')
args = parser.parse_args()
# 从配置文件和检查点文件构建模型
model = init_segmentor(args.config, args.checkpoint, device=args.device)
# 测试单张图像
result = inference_segmentor(model, args.img)
# 显示并保存结果
show_result_pyplot(model, args.img, result, get_palette(args.palette), out_file=args.out_file)
if __name__ == '__main__':
main()
0 warning 0 error