使用RealESRGAN模型时遇AttributeError:NoneType无load_state_dict属性求助
RealESRGAN模型加载报错:AttributeError: 'NoneType' object has no attribute 'load_state_dict'
问题背景
我正在用Python构建图像放大后端,基于RealESRGAN模型开发,测试用简化版Flask后端代码如下:
import os from flask import Flask, request, jsonify from flask_cors import CORS from realesrgan import RealESRGANer from PIL import Image import numpy as np import io app = Flask(__name__) CORS(app) # 初始化RealESRGAN模型 model_path = "./RealESRGAN_x4plus_anime_6B.pth" model = RealESRGANer(scale=4, model_path=model_path) @app.route('/upscale', methods=['POST']) def upscale_image(): if 'image' not in request.files: return jsonify({"error": "No image provided"}), 400 file = request.files['image'] try: # 读取图像文件 img = Image.open(file.stream).convert('RGB') # 转numpy数组并放大 img_array = np.array(img) upscaled_image = model.predict(img_array) # 转回PIL格式 upscaled_image = Image.fromarray(upscaled_image) # 保存为字节流返回 img_byte_arr = io.BytesIO() upscaled_image.save(img_byte_arr, format='PNG') img_byte_arr.seek(0) return jsonify({"message": "Image upscaled successfully", "upscaled_image": img_byte_arr.getvalue().decode('latin1')}) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True)
运行时触发以下错误:
model.load_state_dict(loadnet[keyname], strict=True)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'load_state_dict'
已尝试的调试操作
- 模型加载:手动编写模型加载代码尝试修复(代码如下)
# 检测设备(GPU/CPU) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 初始化RealESRGANer self.model = RealESRGANer( scale=4, # 放大倍数 model_path=model_path, # 预训练权重路径 tile=0, # 不使用分块 tile_pad=10, # 分块时的 padding pre_pad=0, # 预 padding half=False, # 关闭半精度避免问题 device=device # 使用检测到的设备 ) # 加载权重到模型结构 state_dict = torch.load(model_path, map_location=device) # 确保state_dict包含'params_ema' if "params_ema" in state_dict: self.model.model.load_state_dict(state_dict["params_ema"], strict=True) else: raise ValueError("The state_dict does not contain 'params_ema'. Please check the model file.") # 设置模型为评估模式(推理必备) self.model.model.eval() - 文件路径:用
print(os.path.exists("./RealESRGAN_x4plus_anime_6B.pth"))验证路径正确性 - 替代模型:测试了另一版本的RealESRGAN模型文件
解决建议
1. 验证模型文件完整性
报错核心是模型加载时返回None,大概率是模型文件损坏或下载不完整:
- 重新下载对应模型文件,核对文件大小与官方发布的一致
- 若官方提供校验值,用校验工具验证文件完整性
2. 修复模型初始化逻辑
调整RealESRGANer的初始化流程,先手动验证权重文件有效性,再完成模型加载:
import torch import os from realesrgan import RealESRGANer device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model_path = os.path.abspath("./RealESRGAN_x4plus_anime_6B.pth") # 先检查权重文件是否能正常加载 try: state_dict = torch.load(model_path, map_location=device) # 检查权重结构是否符合要求 if not ("params_ema" in state_dict or "params" in state_dict): raise ValueError("模型权重文件结构异常,缺少必要的参数键") except Exception as e: print(f"加载模型权重失败: {str(e)}") exit(1) # 初始化RealESRGANer model = RealESRGANer( scale=4, model_path=model_path, tile=0, tile_pad=10, pre_pad=0, half=False, device=device ) # 手动加载权重(覆盖内部可能失败的加载逻辑) if "params_ema" in state_dict: model.model.load_state_dict(state_dict["params_ema"], strict=True) else: model.model.load_state_dict(state_dict["params"], strict=True) model.model.eval()
3. 核对依赖版本兼容性
RealESRGAN对PyTorch、torchvision等依赖版本有严格要求:
- 参考项目官方README安装指定版本的依赖
- 避免使用与模型不兼容的PyTorch版本(如PyTorch 2.x可能需要调整加载逻辑)
4. 使用绝对路径加载模型
相对路径可能因运行目录不同导致文件找不到,改用绝对路径确保定位准确:
import os model_path = os.path.abspath("./RealESRGAN_x4plus_anime_6B.pth") print(f"模型绝对路径: {model_path}") print(f"文件是否存在: {os.path.exists(model_path)}")
内容的提问来源于stack exchange,提问作者ArmandPret-OW
相关产品推荐
相关产品推荐

