MMSegmentation实战
1.训练
1.1训练方式
单卡训练
先配置文件
#在ubuntu命令行中执行
#configParameter文件是我自己整合的,在后面贴出来了
python configParameter.py
#会生成一个自己的配置文件
python tools/train.py [config文件路径]
多卡训练
#配置流程一样,唯一不同的是执行训练的语句有所差别
./tools/dist_train.sh [config文件路径] [GPU数量]
#示例命令:我这里用了3块GPU
./tools/dist_train.sh Zihao-Configs/WHUDataset_DeepLabV3+_20230818.py 3
1.2训练修改
【训练中断】怎么办?!如何实现断点续训?!
①在 ./configs/_base _/default_runtime.py中更改两行代码
第一行是指向上次训练的最后一次权重文件
第二行是将是否继续训练默认为False的设置更改为True
load_from = "./work_dirs/WHUDataset_DeepLabV3+/best_mIoU_iter_21000.pth"
resume = True
②重新配置模型文件,重新执行训练。
配置好resume的参数之后
重新进行一遍训练流程即可!
我的实验流程是根据同济子豪兄流程来做的,所以configParameter.py文件是根据同济子豪兄的JupyterNotebook写的
原链接如下:
https://github.com/TommyZihao/MMSegmentation_Tutorials/tree/main/20230816
我自己整理成了一份python文件,文件名是configParameter.py,在这个博客中贴出
https://blog.csdn.net/ArcGis_Niu/article/details/133317054?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22133317054%22%2C%22source%22%3A%22ArcGis_Niu%22%7D
#在命令行中执行
python configParameter.py
-----------------------------------------------------------------------
#多卡训练,指定配置文件 最后的数字3是指定gpu数
./tools/dist_train.sh Zihao-Configs/WHUDataset_DeepLabV3+_20230818.py 3
-------------------------------------------------------------------------
2.测试
运行test.py即可
单卡进行测试
python tools/test.py [配置文件路径] [权重文件路径]
输出结果:
多卡测试
./tools/dist_test.sh [配置文件路径] [权重文件路径] [GPU数]
3.预测
也非常简单,运行以下代码即可进行单幅图像预测:
python predict.py #predict.py文件代码在下文中贴出
#这是predict.py文件的代码
#主要作用是对单幅图像进行预测
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from mmseg.apis import init_model, inference_model, show_result_pyplot
import mmcv
import cv2
#载入模型配置文件
config_file = './Zihao-Configs/WHUDataset_UNet_20230818.py'
# 模型 checkpoint 权重文件
checkpoint_file = './work_dirs/WHUDataset-UNet/iter_40000.pth'
#提取epoch数
import re
pattern = r'(\d+)'
match = re.search(pattern, checkpoint_file)
if match:
epoch = match.group(1)
print(epoch)
else:
print("No number found in the file path.")
# device = 'cpu'
device = 'cuda:0'
model = init_model(config_file, checkpoint_file, device=device)
img_path = '需要预测的图像的路径'
img_bgr = cv2.imread(img_path)
plt.figure(figsize=(8, 8))
plt.imshow(img_bgr[:,:,::-1])
plt.show()
result = inference_model(model, img_bgr)
result.keys()
pred_mask = result.pred_sem_seg.data[0].cpu().numpy()
pred_mask.shape
np.unique(pred_mask)
plt.figure(figsize=(8, 8))
plt.imshow(pred_mask)
save_path='./outputs/spaceNet50_'+epoch+'_predict.png'
plt.figure(figsize=(8, 8))
plt.imshow(pred_mask)
plt.savefig(save_path)
plt.show()
4.训练日志可视化
可视化还没有研究通,让我弄好了再发上来和大家交流~~
未完待续……