【AI达人创造营第二期】以RCAN模型对遥感图像超分辨率重建,可以直接体验!
时间:2025-07-22 | 作者: | 阅读:0本文介绍基于Paddle训练的RCAN模型用于遥感图像四倍超分辨率重建的项目。涵盖项目背景,说明超分在遥感影像应用中的意义,还详述准备工作(克隆代码、准备数据、安装依赖等)、模型训练与预测过程,以及如何快速体验模型对图像的重建效果。
以RCAN模型对遥感图像超分辨率重建,可以直接体验!
一、项目背景
意义与应用场景:单幅影像超分辨率重建一直是low-level视觉领域中一个比较热门的任务,其可以成为修复老电影、老照片的技术手段,也可以为图像分割、目标检测等下游任务提供质量较高的数据。应用的场景也比较广泛,例如:在船舶检测和分类等诸多遥感影像应用中,提高遥感影像分辨率具有重要意义。
如下表所示,当你需要对遥感图像中的车辆进行检测时,哪一种图像更好呢?当你要进行车道线提取时,哪一种的图像你更喜欢呢?
- 答案是显而易见的,但如果你只有左边这列的低分辨率影像呢??你该何去何从(手动狗头)?不要怕,可以尝试用超分辨率重建来帮你!本项目将展示用paddle训练的RCAN模型来重建四倍的遥感影像,先上效果图!
- 效果是不是不错呢?那就往下看看这怎么训练和预测的吧。注意:本项目不涉及paddlel复现RCAN模型的原理,若感兴趣的小伙伴可以去这个基于PaddleGAN框架复现超分辨率网络RCAN并对遥感影像超分项目看看
二、准备工作
- 在进行训练之前首先要克隆代码、准备数据以及安装环境依赖
- 之前我已经在github以及gitee上上传了相应的代码,做成了paddle复现RCAN模型的仓库
- github地址:https://github.com/kongdebug/RCAN-Paddle
- gitee地址:https://gitee.com/jia_jianghao_gege/RCAN-Paddle
- 项目所用数据集地址:https://aistudio.baidu.com/aistudio/datasetdetail/129011 ,简介有介绍该数据集如何产生
# 从码云上克隆仓库!git clone https://gitee.com/jia_jianghao_gege/RCAN-Paddle.git登录后复制 ? ? ? ?
正克隆到 'RCAN-Paddle'...remote: Enumerating objects: 457, done.remote: Total 457 (delta 0), reused 0 (delta 0), pack-reused 457接收对象中: 100% (457/457), 25.47 MiB | 2.07 MiB/s, 完成.处理 delta 中: 100% (77/77), 完成.检查连接... 完成。登录后复制 ? ? ? ?In [?]
# 解压数据集到指定文件夹中,大概一分钟!unzip -oq data/data129011/RSdata_for_SR.zip -d RCAN-Paddle/data/登录后复制 ? ?
- 同时还需要设置训练的配置文件,我已经写好放在work文件夹里,可以执行下面的命令复制文件到指定文件夹
# 运行下列命令,将准备好的配置文件复制到RCAN-Paddle/configs文件夹下!cp work/rcan_x4_rssr.yaml RCAN-Paddle/configs/登录后复制 ? ?In [?]
# 安装依赖%cd RCAN-Paddle/!pip install -r requirements.txt登录后复制 ? ?
三、模型训练与预测
- 由于RCAN模型很难训练,很容易崩,所以使用我预训练好的checkpoint来接着训练,checkpoint保存在work/checkpoint文件夹里
- 运行下列命令即可训练,训练的模型权重文件保存在RCAN-Paddle/output_dir/的文件夹下
# 运行该语句训练模型!python -u tools/main.py --config-file configs/rcan_x4_rssr.yaml --resume ../work/checkpoint/iter_270000_checkpoint.pdparams登录后复制 ? ?
- 训练达到预期效果后,可以使用模型来测试。我已经提前将权重文件放在work/weight文件夹下,运行下行代码对测试集test_LR进行测试
- 测试的结果也保存在output_dir文件夹下 测试的结果:PSNR:inf SSIM:0.9709,属于有点高了,应该是PaddleGAN的bug,但是本项目是为了展示对遥感影像重建的效果的,无伤大雅,要是想知道怎么解决,参照这个基于PaddleGAN框架复现超分辨率网络RCAN并对遥感影像超分项目,这里不做重复
# 执行预测,注意,若要保存结果,将rcan_x4_rssr.yaml文件中的第84行设置为True%cd RCAN-Paddle/!python -u tools/main.py --config-file configs/rcan_x4_rssr.yaml --evaluate-only --load ../work/weight/rcan_rssr_x4.pdparams登录后复制 ? ? ? ?
/home/aistudio/RCAN-Paddle[02/22 16:23:07] ppgan INFO: Configs: {'total_iters': 400000, 'output_dir': 'output_dir/rcan_x4_rssr-2022-02-22-16-23', 'min_max': (0.0, 255.0), 'model': {'name': 'BaseSRModel', 'generator': {'name': 'RCAN'}, 'pixel_criterion': {'name': 'L1Loss'}}, 'dataset': {'train': {'name': 'SRDataset', 'gt_folder': 'data/RSdata_for_SR/trian_HR', 'lq_folder': 'data/RSdata_for_SR/train_LR/x4', 'num_workers': 4, 'batch_size': 16, 'scale': 4, 'preprocess': [{'name': 'LoadImageFromFile', 'key': 'lq'}, {'name': 'LoadImageFromFile', 'key': 'gt'}, {'name': 'Transforms', 'input_keys': ['lq', 'gt'], 'pipeline': [{'name': 'SRPairedRandomCrop', 'gt_patch_size': 192, 'scale': 4, 'keys': ['image', 'image']}, {'name': 'PairedRandomHorizontalFlip', 'keys': ['image', 'image']}, {'name': 'PairedRandomVerticalFlip', 'keys': ['image', 'image']}, {'name': 'PairedRandomTransposeHW', 'keys': ['image', 'image']}, {'name': 'Transpose', 'keys': ['image', 'image']}, {'name': 'Normalize', 'mean': [0.0, 0.0, 0.0], 'std': [1.0, 1.0, 1.0], 'keys': ['image', 'image']}]}]}, 'test': {'name': 'SRDataset', 'gt_folder': 'data/RSdata_for_SR/test_HR', 'lq_folder': 'data/RSdata_for_SR/test_LR/x4', 'scale': 4, 'preprocess': [{'name': 'LoadImageFromFile', 'key': 'lq'}, {'name': 'LoadImageFromFile', 'key': 'gt'}, {'name': 'Transforms', 'input_keys': ['lq', 'gt'], 'pipeline': [{'name': 'Transpose', 'keys': ['image', 'image']}, {'name': 'Normalize', 'mean': [0.0, 0.0, 0.0], 'std': [1.0, 1.0, 1.0], 'keys': ['image', 'image']}]}]}}, 'lr_scheduler': {'name': 'CosineAnnealingRestartLR', 'learning_rate': 0.0001, 'periods': [100000, 100000, 100000, 100000], 'restart_weights': [1, 1, 1, 1], 'eta_min': 1e-07}, 'optimizer': {'name': 'Adam', 'net_names': ['generator'], 'beta1': 0.9, 'beta2': 0.99}, 'validate': {'interval': 5000, 'save_img': True, 'metrics': {'psnr': {'name': 'PSNR', 'crop_border': 4, 'test_y_channel': True}, 'ssim': {'name': 'SSIM', 'crop_border': 4, 'test_y_channel': True}}}, 'log_config': {'interval': 100, 'visiual_interval': 500}, 'snapshot_config': {'interval': 5000}, 'export_model': [{'name': 'generator', 'inputs_num': 1}], 'is_train': False, 'profiler_options': None, 'timestamp': '-2022-02-22-16-23'}W0222 16:23:07.502808 7250 device_context.cc:404] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 10.1, Runtime API Version: 10.1W0222 16:23:07.507916 7250 device_context.cc:422] device: 0, cuDNN Version: 7.6./opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations if data.dtype == np.object:[02/22 16:23:14] ppgan.engine.trainer INFO: Loaded pretrained weight for net generator[02/22 16:23:14] ppgan.engine.trainer INFO: Test iter: [0/420][02/22 16:23:53] ppgan.engine.trainer INFO: Test iter: [100/420][02/22 16:24:33] ppgan.engine.trainer INFO: Test iter: [200/420][02/22 16:25:12] ppgan.engine.trainer INFO: Test iter: [300/420][02/22 16:25:52] ppgan.engine.trainer INFO: Test iter: [400/420][02/22 16:25:59] ppgan.engine.trainer INFO: Metric psnr: inf[02/22 16:25:59] ppgan.engine.trainer INFO: Metric ssim: 0.9709登录后复制 ? ? ? ?
四、快速体验
- 定义了使用RCAN模型的预测类,可以直接上传要预测的图像到指定的文件夹,然后运行代码,输出预测结果
- 接下来的示例,是对work/example/inputs文件夹下的图像进行重建
# 定义使用RCAN模型预测的类RCANPredictor,需要输入参数:# output: 模型输出保存的文件夹# weight_path: 模型权重文件所在的路径import osimport cv2import globimport numpy as npfrom PIL import Imagefrom tqdm import tqdmimport paddle from ppgan.models.generators import RCANfrom ppgan.apps.base_predictor import BasePredictorfrom ppgan.utils.logger import get_loggerclass RCANPredictor(BasePredictor): def __init__(self, output='../work/example/output', weight_path=None): self.input = input self.output = os.path.join(output, 'RCAN') self.model = RCAN() state_dict = paddle.load(weight_path) state_dict = state_dict['generator'] self.model.load_dict(state_dict) self.model.eval() def norm(self, img): img = np.array(img).transpose([2, 0, 1]).astype('float32') / 1.0 return img.astype('float32') def denorm(self, img): img = img.transpose((1, 2, 0)) return (img * 1).clip(0, 255).astype('uint8') def run_image(self, img): if isinstance(img, str): ori_img = Image.open(img).convert('RGB') elif isinstance(img, np.ndarray): ori_img = Image.fromarray(img).convert('RGB') elif isinstance(img, Image.Image): ori_img = img img = self.norm(ori_img) x = paddle.to_tensor(img[np.newaxis, ...]) with paddle.no_grad(): out = self.model(x) pred_img = self.denorm(out.numpy()[0]) pred_img = Image.fromarray(pred_img) return pred_img def run(self, input): if not os.path.exists(self.output): os.makedirs(self.output) pred_img = self.run_image(input) out_path = None if self.output: try: base_name = os.path.splitext(os.path.basename(input))[0] except: base_name = 'result' out_path = os.path.join(self.output, base_name + '.png') pred_img.save(out_path) logger = get_logger() logger.info('Image saved to {}'.format(out_path)) return pred_img, out_path登录后复制 ? ?
- 定义好预测的类之后,接下来实例化预测类并对文件夹下的图像进行预测
- 在预测的过程中,展示输入的低分辨率图像与预测的图像
- 预测的结果保存在指定的文件夹的RCAN文件夹中
import matplotlib.pyplot as plt%matplotlib inline%cd ~ # 输出预测结果的文件夹output = r'work/example/output' # 模型路径weight_path = r”work/weight/rcan_rssr_x4.pdparams“# 待输入的低分辨率影像位置input_dir = r”work/example/inputs“ paddle.device.set_device(”gpu:0“) # 若是cpu环境,则替换为 paddle.device.set_device(”cpu“)predictor = RCANPredictor(output, weight_path) # 实例化filenames = [f for f in os.listdir(input_dir) if f.endswith('.png')]for filename in filenames: imgPath = os.path.join(input_dir, filename) outImg, _ = predictor.run(imgPath) # 预测 # 可视化 image = Image.open(imgPath) plt.figure(figsize=(10, 6)) plt.subplot(1,2,1), plt.title('Input') plt.imshow(image), plt.axis('off') plt.subplot(1,2,2), plt.title('Output') plt.imshow(outImg), plt.axis('off') plt.show()登录后复制 ? ? ? ?
/home/aistudio[02/22 19:38:30] ppgan INFO: Image saved to work/example/output/RCAN/mediumresidential44.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:34] ppgan INFO: Image saved to work/example/output/RCAN/harbor13.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:38] ppgan INFO: Image saved to work/example/output/RCAN/runway16.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:43] ppgan INFO: Image saved to work/example/output/RCAN/storagetanks37.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:47] ppgan INFO: Image saved to work/example/output/RCAN/intersection16.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:52] ppgan INFO: Image saved to work/example/output/RCAN/river23.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:38:57] ppgan INFO: Image saved to work/example/output/RCAN/parkinglot61.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:39:02] ppgan INFO: Image saved to work/example/output/RCAN/sparseresidential23.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:39:07] ppgan INFO: Image saved to work/example/output/RCAN/overpass63.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
[02/22 19:39:12] ppgan INFO: Image saved to work/example/output/RCAN/tenniscourt19.png登录后复制 ? ? ? ?
<Figure size 720x432 with 2 Axes>登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制登录后复制 ? ? ? ? ? ? ? ?
福利游戏
相关文章
更多-
- 电脑蓝屏代码 PAGEFILE_INSUFFICIENT_ERROR怎么回事儿
- 时间:2025-07-22
-
- 多模态AI支持语音对话吗 多模态AI语音输入输出能力说明
- 时间:2025-07-22
-
- 2021 CCF BDCI基于飞桨实现花样滑冰选手骨骼点动作识别-B榜第3名方案
- 时间:2025-07-22
-
- 如何用夸克AI大模型训练写作模型售卖 夸克AI大模型模型定制变现方式
- 时间:2025-07-22
-
- 豆包AI能干嘛 豆包AI以图生图功能实测教程
- 时间:2025-07-22
-
- 草原偶遇“最美旅行车” 余承东亲测享界S9T智慧电动门
- 时间:2025-07-22
-
- 目前最受欢迎的AI内容创作工具排行榜及优缺点
- 时间:2025-07-22
-
- 电脑蓝屏时屏幕出现乱码 是显卡问题还是显示器故障
- 时间:2025-07-22
大家都在玩
大家都在看
更多-
- 剑桥数字货币交易所:开启资产新纪元
- 时间:2025-07-22
-
- 称亲自开上了陡坡 余承东晒享界S9T实车:颜值与实力并存
- 时间:2025-07-22
-
- MSN币未来展望:机遇与挑战并存
- 时间:2025-07-22
-
- 电脑蓝屏时屏幕出现乱码 是显卡问题还是显示器故障
- 时间:2025-07-22
-
- Switch 2 OLED中框遭曝光:闲鱼惊现研发样品
- 时间:2025-07-22
-
- 电脑安装软件时提示 “权限不足”,怎么获取权限?
- 时间:2025-07-22
-
- 全球首架“三证齐全”吨级以上eVTOL交付:用于低空货运场
- 时间:2025-07-22
-
- vivo在印度市场连续4季度销量夺冠:Q2狂销810万台
- 时间:2025-07-22