基于Random Forest的Python图像缩放优化:生成完整图像
基于Random Forest的图像超分:从单块到整图生成的修改方案
核心思路
现有代码仅处理单块图像,要生成完整可识别的图像片段,需通过重叠分块滑动处理+加权拼接解决块间接缝问题,最后对齐尺寸并计算评估指标。以下是具体实现步骤:
1. 重叠分块:分割低分辨率图像
为避免拼接后出现明显接缝,采用重叠滑动窗口策略:
- 设定低分辨率块大小(如
3x3),对应高分辨率块大小为块尺寸×放大倍数(如放大2倍则为6x6) - 滑动步长设为块尺寸的1/2,让相邻块重叠50%,后续通过加权融合消除接缝
2. 批量预测所有图像块
将分割得到的低分辨率块展平后,输入训练好的Random Forest模型,得到对应高分辨率块的预测结果,同时记录每个块在原图中的位置,方便后续拼接。
3. 加权拼接:消除块间接缝
直接拼接会产生接缝,因此对重叠区域采用中心加权策略:块中心区域权重高,边缘区域权重低,叠加后归一化得到平滑的完整图像。
4. 尺寸对齐与指标计算
将拼接后的图像裁剪至与原始高分辨率图像一致的尺寸,再用PSNR、SSIM指标进行量化对比。
示例代码(灰度图像场景)
import numpy as np from skimage.metrics import peak_signal_noise_ratio, structural_similarity # 自定义参数 SCALE = 2 # 图像放大倍数 LR_BLOCK_SIZE = 3 # 低分辨率块尺寸 HR_BLOCK_SIZE = LR_BLOCK_SIZE * SCALE STEP = LR_BLOCK_SIZE // 2 # 滑动步长 def split_lr_blocks(lr_img): """分割低分辨率图像为重叠块,记录每个块的位置""" blocks = [] positions = [] h, w = lr_img.shape[:2] # 遍历滑动窗口生成块 for y in range(0, h - LR_BLOCK_SIZE + 1, STEP): for x in range(0, w - LR_BLOCK_SIZE + 1, STEP): block = lr_img[y:y+LR_BLOCK_SIZE, x:x+LR_BLOCK_SIZE].flatten() blocks.append(block) positions.append((y, x)) return np.array(blocks), positions def reconstruct_hr_image(predictions, positions, target_shape): """加权融合高分辨率块,生成完整图像""" hr_img = np.zeros(target_shape, dtype=np.float32) weight_map = np.zeros(target_shape, dtype=np.float32) hr_step = STEP * SCALE # 生成中心加权矩阵(中心权重高,边缘权重低) y_weights = np.linspace(0.1, 1.0, HR_BLOCK_SIZE) y_weights = np.concatenate([y_weights, y_weights[-2::-1]]) if HR_BLOCK_SIZE % 2 == 0 else np.concatenate([y_weights, y_weights[-2::-1]]) y_weights = y_weights.reshape(-1, 1) x_weights = np.linspace(0.1, 1.0, HR_BLOCK_SIZE) x_weights = np.concatenate([x_weights, x_weights[-2::-1]]) if HR_BLOCK_SIZE % 2 == 0 else np.concatenate([x_weights, x_weights[-2::-1]]) x_weights = x_weights.reshape(1, -1) block_weight = y_weights * x_weights # 叠加每个预测块到对应位置 for pred, (y_lr, x_lr) in zip(predictions, positions): y_hr = y_lr * SCALE x_hr = x_lr * SCALE hr_block = pred.reshape(HR_BLOCK_SIZE, HR_BLOCK_SIZE) hr_img[y_hr:y_hr+HR_BLOCK_SIZE, x_hr:x_hr+HR_BLOCK_SIZE] += hr_block * block_weight weight_map[y_hr:y_hr+HR_BLOCK_SIZE, x_hr:x_hr+HR_BLOCK_SIZE] += block_weight # 归一化得到最终图像 hr_img = hr_img / weight_map return hr_img.astype(np.uint8) # 主流程 # 替换为你的实际图像数据 lr_input = ... # 输入低分辨率图像(单通道灰度图) hr_ground_truth = ... # 原始高分辨率图像 # 分块+预测 lr_blocks, block_positions = split_lr_blocks(lr_input) hr_block_preds = rf_trained_model.predict(lr_blocks) # rf_trained_model为你训练好的随机森林模型 # 重建完整高分辨率图像 predicted_hr = reconstruct_hr_image(hr_block_preds, block_positions, hr_ground_truth.shape) # 裁剪至目标尺寸(处理边界溢出问题) predicted_hr = predicted_hr[:hr_ground_truth.shape[0], :hr_ground_truth.shape[1]] # 计算评估指标 psnr = peak_signal_noise_ratio(hr_ground_truth, predicted_hr) ssim = structural_similarity(hr_ground_truth, predicted_hr, data_range=255) print(f"PSNR: {psnr:.2f} dB") print(f"SSIM: {ssim:.4f}")
彩色图像适配方法
如果处理RGB彩色图像,只需对每个通道单独执行分块、预测、拼接操作,最后合并三个通道即可:
# 彩色图像处理示例 predicted_hr_rgb = np.zeros_like(hr_ground_truth) for channel in range(3): lr_channel = lr_input[..., channel] lr_blocks, positions = split_lr_blocks(lr_channel) hr_preds = rf_trained_model.predict(lr_blocks) predicted_hr_rgb[..., channel] = reconstruct_hr_image(hr_preds, positions, hr_ground_truth.shape[:2])
关键优化提示
- 块尺寸调整:若预测结果细节不足,可尝试增大低分辨率块尺寸(如
5x5),但会增加计算量 - 步长选择:步长越小,重叠区域越大,接缝越不明显,但预测速度越慢,需根据需求平衡
- 模型优化:若拼接后图像仍模糊,可增加训练样本数量,或调整Random Forest的树数量、深度等超参数
内容的提问来源于stack exchange,提问作者Resa
相关产品推荐
相关产品推荐

