本文介绍基于Paddle训练的RCAN模型用于遥感图像四倍超分辨率重建的项目。涵盖项目背景,说明超分在遥感影像应用中的意义,还详述准备工作(克隆代码、准备数据、安装依赖等)、模型训练与预测过程,以及如何快速体验模型对图像的重建效果。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

意义与应用场景:单幅影像超分辨率重建一直是low-level视觉领域中一个比较热门的任务,其可以成为修复老电影、老照片的技术手段,也可以为图像分割、目标检测等下游任务提供质量较高的数据。应用的场景也比较广泛,例如:在船舶检测和分类等诸多遥感影像应用中,提高遥感影像分辨率具有重要意义。
如下表所示,当你需要对遥感图像中的车辆进行检测时,哪一种图像更好呢?当你要进行车道线提取时,哪一种的图像你更喜欢呢?
| 低分辨率 | 高分辨率 |
|---|---|
| @@##@@ | @@##@@ |
| @@##@@ | @@##@@ |
| 低分辨率 | RCAN重建 | 高分辨率 |
|---|---|---|
| @@##@@ | @@##@@ | @@##@@ |
| @@##@@ | @@##@@ | @@##@@ |
# 从码云上克隆仓库!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), 完成. 检查连接... 完成。
# 解压数据集到指定文件夹中,大概一分钟!unzip -oq data/data129011/RSdata_for_SR.zip -d RCAN-Paddle/data/
# 运行下列命令,将准备好的配置文件复制到RCAN-Paddle/configs文件夹下!cp work/rcan_x4_rssr.yaml RCAN-Paddle/configs/
# 安装依赖%cd RCAN-Paddle/ !pip install -r requirements.txt
# 运行该语句训练模型!python -u tools/main.py --config-file configs/rcan_x4_rssr.yaml --resume ../work/checkpoint/iter_270000_checkpoint.pdparams
# 执行预测,注意,若要保存结果,将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.1
W0222 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模型预测的类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_pathimport 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>










以上就是【AI达人创造营第二期】以RCAN模型对遥感图像超分辨率重建,可以直接体验!的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号