第一次接触SwinIR时,光是环境配置就让我折腾了大半天。记得当时因为一个CUDA版本不兼容的问题,重装了三次驱动才搞定。为了让你们少走弯路,我把完整的配置流程和避坑要点都整理在这里。
建议所有Python项目都使用Anaconda创建独立环境,避免包冲突。我习惯用Miniconda,体积更小巧:
bash复制conda create -n swinir python=3.8 -y
conda activate swinir
这里特别提醒:Python 3.8是最稳定的选择。我测试过3.9和3.10版本,会遇到一些依赖包兼容性问题。环境创建完成后,建议先升级pip:
bash复制python -m pip install --upgrade pip
PyTorch版本选择直接影响后续模型训练。根据我的测试,1.10.0版本在Windows和Linux下表现最稳定:
bash复制pip install torch==1.10.0+cu113 torchvision==0.11.1+cu113 -f https://download.pytorch.org/whl/torch_stable.html
安装后务必验证CUDA是否可用:
python复制import torch
print(torch.cuda.is_available()) # 应该返回True
print(torch.version.cuda) # 应该显示11.3
如果遇到下载慢的问题,可以临时更换国内镜像源。但要注意安装完成后记得恢复默认源,避免影响其他项目:
bash复制pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 安装完成后执行
pip config unset global.index-url
从GitHub克隆SwinIR项目后,不要直接运行requirements.txt。我发现有几个包需要特别处理:
bash复制git clone https://github.com/cszn/KAIR
cd KAIR
pip install -r requirements.txt --no-deps
加上--no-deps参数可以避免自动安装可能冲突的依赖版本。之后手动安装这些关键包:
bash复制pip install opencv-python==4.5.5.64
pip install scikit-image==0.19.3
注意:opencv-python的4.5.5版本与SwinIR的图像处理模块兼容性最好,新版可能导致颜色空间转换异常。
很多人在数据集准备阶段就踩坑,我也不例外。记得第一次训练时因为图像尺寸不匹配,白白浪费了8小时的计算资源。
正确的文件夹结构应该是这样:
code复制DIV2K/
├── HR/
│ ├── 0801.png
│ └── 0802.png
└── LR_bicubic/
├── X2/
│ ├── 0801x2.png
│ └── 0802x2.png
└── X4/
├── 0801x4.png
└── 0802x4.png
关键点:
直接使用原始DIV2K数据集会遇到尺寸不一致问题。建议用这个Python脚本统一处理:
python复制import cv2
import os
def resize_images(input_dir, output_dir, target_size):
os.makedirs(output_dir, exist_ok=True)
for img_name in os.listdir(input_dir):
img = cv2.imread(os.path.join(input_dir, img_name))
h, w = img.shape[:2]
# 确保尺寸是缩放倍数的整数倍
new_h = h - h % scale_factor
new_w = w - w % scale_factor
img = cv2.resize(img, (new_w, new_h))
cv2.imwrite(os.path.join(output_dir, img_name), img)
options/swinir/train_swinir_sr_classical.json需要修改这几个关键参数:
json复制{
"name": "SwinIR",
"scale": 2,
"datasets": {
"train": {
"dataroot_H": "./DIV2K/HR",
"dataroot_L": "./DIV2K/LR_bicubic/X2"
}
},
"network_G": {
"upscale": 2,
"in_chans": 3
}
}
特别提醒:scale和upscale必须保持一致,否则会出现张量维度不匹配的错误。
第一次启动训练时,那个张量维度报错让我记忆犹新。通过反复实验,我总结出这些实战经验。
在Windows上需要修改utils/utils_dist.py:
python复制# 将
dist.init_process_group(backend='nccl')
# 改为
dist.init_process_group(backend='gloo')
这是因为Windows对NCCL支持不完善。修改后启动训练:
bash复制python main_train_psnr.py --opt options/swinir/train_swinir_sr_classical.json
报错1:Tensor size mismatch
code复制RuntimeError: The size of tensor a (96) must match the size of tensor b (0) at non-singleton dimension 3
解决方法:
json复制"datasets": {
"train": {
"phase": "train",
"data_type": "img",
"patch_size": 48
}
}
报错2:CUDA out of memory
降低batch_size和patch_size:
json复制"train": {
"batch_size": 16,
"patch_size": 64
}
建议使用TensorBoard监控训练:
bash复制tensorboard --logdir experiments/swinir_sr_classical/log
重点关注这些指标:
训练完成只是第一步,真正的考验在于模型评估。我整理了完整的评估流程和实用技巧。
使用Set5和Set14数据集评估:
bash复制python main_test_swinir.py --task classical_sr --scale 2 --training_patch_size 48 --model_path experiments/swinir_sr_classical/models/latest_G.pth
预期结果参考:
| 数据集 | PSNR (dB) | SSIM |
|---|---|---|
| Set5 | 38.38 | 0.9612 |
| Set14 | 34.42 | 0.9257 |
准备测试图像时要注意:
评估脚本示例:
python复制from swinir import SwinIR
model = SwinIR(upscale=2, in_chans=3)
model.load_state_dict(torch.load('latest_G.pth'))
img = cv2.imread('test.png')
output = model(img)
用这个代码可以生成对比图:
python复制import matplotlib.pyplot as plt
plt.figure(figsize=(20, 10))
plt.subplot(1, 3, 1)
plt.title("LR Input")
plt.imshow(lr_img)
plt.subplot(1, 3, 2)
plt.title("HR Ground Truth")
plt.imshow(hr_img)
plt.subplot(1, 3, 3)
plt.title("SwinIR Output")
plt.imshow(output_img)
plt.savefig("compare.png")
对于超分辨率任务,建议额外关注高频细节的恢复效果,比如文字边缘、纹理细节等。可以适当调整模型的window_size参数来优化细节表现。