请帮我分析一下,这个报错信息中模型的哪些部分对不上需要修改:Traceback (most recent call last): File…
- User
请帮我分析一下,这个报错信息中模型的哪些部分对不上需要修改:Traceback (most recent call last): File "/home/jianruobing/code/AHMF-main/AHMF-main/test1.py", line 28, in missing, unexpected = model.load_state_dict(checkpoint['state'], strict=False) File "/home/jianruobing/anaconda3/envs/DADA-SR/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1482, in load_state_dict raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( RuntimeError: Error(s) in loading state_dict for DataParallel: size mismatch for module.head.guidance_in.0.weight: copying a param with shape torch.Size([64, 3, 3, 3]) from checkpoint, the shape in current model is torch.Size([64, 3, 5, 5]). size mismatch for module.head.guidance_in.2.1.weight: copying a param with shape torch.Size([64, 256, 5, 5]) from checkpoint, the shape in current model is torch.Size([64, 256, 1, 1]). size mismatch for module.head.guidance_in.2.4.weight: copying a param with shape torch.Size([64, 256, 5, 5]) from checkpoint, the shape in current model is torch.Size([64, 256, 1, 1]). size mismatch for module.up_conv.0.layers.weight: copying a param with shape torch.Size([64, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([64, 256, 5, 5]). size mismatch for module.up_conv.1.weight: copying a param with shape torch.Size([256, 64, 5, 5]) from checkpoint, the shape in current model is torch.Size([256, 64, 1, 1]). size mismatch for module.up_conv.4.weight: copying a param with shape torch.Size([256, 64, 5, 5]) from checkpoint, the shape in current model is torch.Size([256, 64, 1, 1]).
- Assistant
从报错信息来看,主要问题是加载的checkpoint中的权重大小(形状)和当前模型定义中对应层的权重大小不匹配(size mismatch)。具体来说,有几处模块参数的卷积核尺寸不一致:
具体不匹配的部分及大小差异:
-
module.head.guidance_in.0.weight- checkpoint 权重形状:
[64, 3, 3, 3] - 当前模型权重形状:
[64, 3, 5, 5]
问题:卷积核尺寸由3×3变成5×5
- checkpoint 权重形状:
-
module.head.guidance_in.2.1.weight- checkpoint 权重形状:
[64, 256, 5, 5] - 当前模型权重形状:
[64, 256, 1, 1]
- checkpoint 权重形状:
-
- User
- Assistant
- User
.ipynb文件怎么在服务器上运行
- Assistant
在服务器上运行
.ipynb(Jupyter Notebook)文件,可以有多种方式,具体取决于你想如何使用它:
方法1:直接启动Jupyter Notebook服务器(交互式使用)
-
安装 Jupyter Notebook(如果还没有安装)
pip install notebook -
在服务器上启动 Jupyter Notebook
jupyter notebook --no-browser --port=8888--no-browser避免服务器启动时自动打开浏览器(服务器通常没有图形界面)--port=8888指定端口(可以改为其他端口)
-
用 SSH 隧道(端口转发)映射到本地机器 在本地机器打开终端,执行:
ssh -L 8888:localhost:8888 user@your_server_ip这样本地通过
http://localhost:8888就能访问服务器上运行的Jupyter Notebook。 -
复制服务器终端显示的token或者在服务器生成密码 打开浏览器,访问 并输入token或密码,加载你的文件。
-
- User
checkpoint = torch.load('./model_{}.pth'.format(scale), map_location='cpu')
torch.save({'state_dict': checkpoint['state_dict']}, f'./model_x{scale}.pth') 这两句为什么要这么写
- Assistant
这两句代码的作用和写法原因总结如下:
checkpoint = torch.load('./model_{}.pth'.format(scale), map_location='cpu') torch.save({'state_dict': checkpoint['state_dict']}, f'./model_x{scale}.pth')
1. 读取原始checkpoint(权重文件)
checkpoint = torch.load('./model_{}.pth'.format(scale), map_location='cpu')- 这里是加载一个原始的模型权重文件,通常这个文件是训练时保存的完整checkpoint。
map_location='cpu'表示不管原来模型是在GPU还是CPU上训练的,这里都把权重加载到CPU上,防止在没有GPU的机器上加载失败。checkpoint一般是一个字典,里面除了模型权重,还可能保存训练状态、优化器状态、epoch信息等等。
2. 重存权重,且只保留
state_dicttorch.save({'state_dict': checkpoint['state_dict']}, f'./model_x{scale}.pth')- 这句是把之前加载的checkpoint只提取里面的
state_dict保存出来,重新写成只包含state_dict的字典,并保存为新的pth文件。 state_dict是PyTorch模型的核心参数字典,包含所有模型权重和偏置。- 这样做目的是“瘦身”或“净化”原本checkpoint,把训练状态(epoch、优化器参数等)去掉,只保存模型权重,方便直接用加载做推理或继续训练。
- User
能不能帮我将.ipynb文件改成.py文件
- Assistant
当然可以!将一个
.ipynb(Jupyter Notebook) 文件转换成.py(Python 脚本) 文件,有几种方法,下面给你介绍几种常用且简单的方法。
方法1:使用 Jupyter 自带的 nbconvert 工具(命令行)
假设你已经安装了
jupyter,在终端运行:jupyter nbconvert --to script your_notebook.ipynb执行成功后,会在同目录生成一个名为
your_notebook.py的 Python 脚本。
方法2:在 Jupyter Notebook 界面导出
- 打开你的
.ipynb文件 - 点击菜单栏的 File(文件) > Download as(另存为) > Python (.py)
- 下载的文件即为
.py脚本
方法3:用 Python 脚本自动转换(适合批量转换)
你可以写一个小脚本,利用
nbconvert的 API:from nbconvert import PythonExporter import nbformat input_path = 'your_notebook.ipynb' output_path = 'your_script.py' # 读取 notebook 文件 with open(input_path, 'r', encoding='utf-8') as f: notebook_node = nbformat.read(f, as_version=4) # 创建 exporter exporter = PythonExporter() source, _ = exporter.from_notebook_node(notebook_node) # 保存为 py 文件 with open(output_path, 'w', encoding='utf-8') as f: f.write(source) print(f'Converted {input_path} to {output_path}') - 打开你的
- User
- Assistant
- User
- Assistant
你的报错是 numpy 在导入 C 语言扩展时失败,提示缺少
libcblas.so.3这个共享库,导致 numpy 无法加载,进而导致 PyTorch 也导入失败。报错核心是:
ImportError: libcblas.so.3: cannot open shared object file: No such file or directory这是 BLAS 线性代数库的动态链接库,numpy 和 PyTorch 都依赖它。
解决办法:
1. 安装 BLAS 库
在 Linux 系统(Ubuntu、Debian 等)可以安装下面的包:
sudo apt-get update sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev或者更简单直接安装:
sudo apt-get install libopenblas-dev确认这些库包含了
libcblas.so.3,安装完成后重启你的终端,再试运行。
2. 检查环境变量 LD_LIBRARY_PATH
- User
能不能用pip安装
- Assistant
你这个错误主要是缺少系统级的
libcblas.so.3动态库。这个库是 BLAS(Basic Linear Algebra Subprograms)实现,pip 是安装 Python 包的工具,无法安装系统级的共享库,所以单靠pip是无法解决这个依赖缺失的。
为什么不能用 pip 安装?
libcblas.so.3是操作系统提供的基础线性代数库,通常由类似libblas、libopenblas、libatlas等系统包提供。- pip 管理的是 Python 包,如
numpy本身,但它依赖的底层C库需要通过操作系统的软件包管理器安装(apt/yum/…)或者手动编译安装。
你可以用 pip 做什么?
如果你想尝试修复 numpy,可以尝试重装 numpy:
pip uninstall numpy pip install numpy但如果系统缺少
libcblas.so.3,这个错误依然会出现。
推荐做法
- Ubuntu/Debian 系统安装依赖:
sudo apt update sudo apt install libopenblas-dev- CentOS/RHEL 系统安装依赖:
sudo yum install openblas-devel- :
- User
- Assistant
你这段代码本身是纯 Python 代码,没有直接调用 libcblas.so.3 之类的共享库,也没有显式使用低层线性代数函数。
但是实际运行时,你的代码导入了以下依赖:
numpy(用于数组操作)torch(PyTorch,用于模型构建和推理)ahmf(自定义模型)PIL(图像处理)- 以及你自定义的
imresize函数
libcblas.so.3 是什么?
libcblas.so.3是 BLAS(Basic Linear Algebra Subprograms)库的实现之一,提供高效的底层矩阵运算接口。它属于系统级的数学库。
为什么报错与代码有关?
虽然你的代码中没有直接写调用
libcblas.so.3,但:- numpy 依赖底层BLAS来加速矩阵与向量运算。
- PyTorch 在CPU上也可能依赖BLAS(或者类似的底层数学库)。
- 因此,当你导入或运行
numpy和torch时,Python内部调用许多C/C++底层扩展,这些扩展在加载时会链接BLAS库。
如果系统找不到
libcblas.so.3,numpy加载底层扩展时会失败,报错提示缺少该库,从而导致整个程序无法运行。
总结
- 你的代码没直接写调用
libcblas.so.3,但是间接依赖它(通过 numpy 和 torch)。 - 这个库是numpy和PyTorch等科学计算库底层必须的动态库。
- 如果缺少它,导入 numpy 或 torch 会失败(你之前的报错就是典型表现)。
解决方法再提醒下
- 安装系统BLAS库,例如Ubuntu下:
sudo apt install libopenblas-dev
- User
我其他的代码执行numpy的这些代码都没有出问题
- Assistant
你其他代码执行numpy没问题,但当前代码报错找不到
libcblas.so.3,这种情况通常有以下几种可能:
1. 你执行此代码的环境和其他代码的环境不一样
- 你用的可能是不同的Python环境(不同的conda环境、虚拟环境或系统Python)
- 导致当前环境内的numpy或PyTorch依赖的底层库未正确安装或环境变量未配置好
建议:
-
在出现问题的环境终端中,运行以下命令确认numpy版本和路径:
python -c "import numpy; print(numpy.__version__); print(numpy.__file__)" -
与你其他能正常运行的环境做对比,确认是否处于不同环境
2. 脚本运行时的工作目录和其他代码运行目录不同
- 有时如果你进入了numpy源码目录下执行,或者当前目录里有和numpy重名的文件夹(比如名叫
numpy的目录),会导致import出错 - 之前错误信息中也提示“you should not try to import numpy from its source directory”
建议:
- User
Traceback (most recent call last): File "test.py", line 41, in model = AHMF(scale, act='PReLU', in_channels=1, guidance_channels=3) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 328, in init FuseNet(num_features=64, reduction_ratio=4, act=self.act, norm=None) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 287, in init self.res_conv = ResNet(num_features=num_features, act=act, norm=norm) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 70, in init self.act = get_act(act=act) File "/home/jianruobing/code/AHMF-main/AHMF-test/common.py", line 126, in get_act "silu": nn.SiLU(inplace=True), AttributeError: module 'torch.nn' has no attribute 'SiLU'
- Assistant
这个报错提示:
AttributeError: module 'torch.nn' has no attribute 'SiLU'说明你使用的 PyTorch 版本不包含
torch.nn.SiLU这个激活函数。
原因分析
SiLU(Swish 激活函数)是在 PyTorch 1.7 以后新增的函数,旧版本中没有torch.nn.SiLU。- 你当前环境中 PyTorch 版本比较旧,或者由于版本问题导致无法使用。
解决方案
1. 升级 PyTorch 到较新的版本(推荐)
升级到 PyTorch 1.7 及以上版本即可支持
nn.SiLU。pip install --upgrade torch torchvision或者使用 conda:
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch根据你的 CUDA 版本选择合适的 cudatoolkit。
确认升级后,Python 交互环境中执行:
import torch.nn as nn print(nn.SiLU)如果不报错,表示升级成功。
2. 如果不能升级,自己实现 SiLU(兼容旧版本)
你可以在
common.py中用下面代码替代 : - User
- Assistant
你需要把第一段代码中模型定义和加载权重的部分,替换到第二段代码中已有的模型定义和加载部分。代码中你已经写好:
scale = 4 model = AHMF(scale=scale, act='PReLU', in_channels=1, guidance_channels=3) # 按需补充参数,和第一段代码一致 model = DataParallel(model).cuda() ckpt_path = '/home/jianruobing/code/AHMF-main/AHMF-test/model_x{}.pth'.format(scale) checkpoint = torch.load(ckpt_path, map_location='cpu') model.load_state_dict(checkpoint['state_dict']) model.eval()这段完全等价于第一段代码:
scale = 4 model = AHMF(scale, act='PReLU', in_channels=1, guidance_channels=3) checkpoint = torch.load('./model_x{}.pth'.format(scale), map_location='cpu') model.load_state_dict(checkpoint['state_dict']) model.cuda().eval() - User
- Assistant
你遇到的这个报错是典型的 PyTorch 模型权重加载时的 键(key)不匹配 问题,具体表现为:
- Missing keys:模型定义里有但 checkpoint 里没有的参数名
- User
- Assistant
- User
这个代码不需要imresize,我已经读取了其中的lr图像
- Assistant
明白了!既然你已经有了
lr(低分辨率图像)图像,就确实没必要再调用imresize来做缩放。你可以直接用已有的
lr图像,并根据需要做相应的预处理即可。
修改建议
-
移除关于
imresize的定义和调用部分。 -
把代码中原先用
imresize得到的lr和lr_up改成直接读取或使用已有的低分辨率图。
举个示例,从你的循环里:
# 之前调用了 imresize 降采样和上采样,去掉 # lr = imresize(dep, 1/scale) # 这行删掉 # lr_up = imresize(lr, scale) # 这行删掉 # 你已经有低分辨率图 lr_img,可直接用它(假设读取后处理为Tensor) # 假设你从文件里读取了低分辨率图,转成Tensor,归一化后扩展维度 # 这里示例变量名叫 lr_img(numpy数组) # 举例(根据你的实际代码调整读取方式): lr_img = ... # 直接读取的低分辨率图,形状如 (H,W) 或 (C,H,W) lr = torch.from_numpy(lr_img.astype(np.float32) / 255.0) if lr.ndim == 2: # 单通道 lr = lr.unsqueeze(0) # 变成 (1,H,W) lr = lr.unsqueeze(0).cuda() # 扩 batch 维度 (1, C, H, W) -
- User
调用的lr图像就是输入的*_depth_x4.{ext}
- Assistant
- User
- Assistant
- User
上述给你的代码报错:Traceback (most recent call last): File "test2.py", line 146, in lr_up = imresize(lr, scale) File "test2.py", line 139, in imresize resized = resized.transpose(2, 0, 1) ValueError: axes don't match array 请帮我修改代码
- Assistant
报错原因是
imresize函数里对resized调用了.transpose(2, 0, 1),但resized并不是三维数组,导致了axes不匹配。问题常见于输入的img是二维单通道图像,经过cv2.resize后,返回二维数组,没有第三个通道维,也就是说resized是(H, W),而不是(H, W, C)。
解决方案
在
imresize中判断输入是否为二维单通道图像,按对应维度处理resized。示例如下:def imresize(img, scalar_scale): if img.ndim == 2: # 单通道二维图像,resize结果为二维,不用转置 h, w = img.shape new_h, new_w = int(h * scalar_scale), int(w * scalar_scale) resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR) return resized elif img.ndim == 3: # 多通道三维图像,转置到 H,W,C 再resize,再转回 C,H,W h, w = img.shape[1], img.shape[2] new_h, new_w = int(h * scalar_scale), int(w * scalar_scale) img_hw_c = img.transpose(1, 2, 0) resized = cv2.resize(img_hw_c, (new_w, new_h), interpolation=cv2.INTER_LINEAR) resized = resized.transpose(2, 0, 1) return resized else: raise ValueError('imresize input must be 2D or 3D array') - User
Traceback (most recent call last): File "test2.py", line 171, in out = model(inputs)['img_out'] File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 363, in forward tmp = self.fuse_conv[i](depth=depth_out[3 - i], File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 292, in forward depth, guide = self.attention_layer(depth=depth, guidance=guide) File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 272, in forward fuse_feature = self.squeeze(torch.cat((depth, guidance), 1)) RuntimeError: Tensors must have same number of dimensions: got 3 and 4
- Assistant
报错信息:
RuntimeError: Tensors must have same number of dimensions: got 3 and 4发生在
torch.cat((depth, guidance), 1)处,说明这两个张量depth和guidance维度不匹配,一个是3维,一个是4维。
可能原因
- 维度不一致:
- 3维通常是(C, H, W)
- 4维通常是(B, C, H, W),带了batch维
- 在
forward函数里输入的张量中depth和guidance的维度不匹配,导致拼接失败。
一般排查建议
- 维度不一致:
- User
- Assistant
你给的这段代码中,确实是有用到batch维度的。
具体来说:
这几行代码:
lr, lr_up, dep, rgb = lr.unsqueeze(0), lr_up.unsqueeze(0), dep.unsqueeze(0), rgb.unsqueeze(0)- 这里的
unsqueeze(0)是在第0维增加一个维度,也就是给所有的张量加上了 batch维度。 - 例如,如果
dep是形状(C, H, W),执行dep.unsqueeze(0)后它变成(1, C, H, W),第一个维度就是batch大小,设为1。
为什么要加batch维?
-
PyTorch的模型通常接收的输入张量都是 4维:
(batch_size, channels, height, width) -
即使你只有一张图要预测,仍需加上这个batch维。
代码中何处用到了batch维?
- 通过
unsqueeze(0)给所有张量加了batch维 - 模型输入时,
inputs = {...}里的dep、rgb、lr、lr_up均是4维张量 - 模型内部的所有层也会默认期望第0维是batch
总结
- 你的代码已经正确地使用了batch维度,batch大小始终是1(单张图片推理)
- 如果你有多张图片需要一起处理,可以把多张数据拼成更大的batch,形状类似
(N, C, H, W),这里N就是batch size
如果还有关于batch维度使用或其他问题,欢迎继续交流!
- 这里的
- User
- Assistant
从你打印的维度来看:
dep:[1, 1, 384, 512](batch, channel, height, width) —— 正确,4维rgb:[1, 3, 384, 512](batch, channel, height, width) —— 正确,4维lr:[1, 96, 128]三维,缺少 batch 或 channel 维度?lr_up:[1, 384, 512]三维,缺少 batch 或 channel 维度?
问题所在:
lr和lr_up是3维张量,缺少 batch 或者 channel 维,导致模型中期望4维的输入变成了3维,引起维度错误。
解决方法:
你需要确保
lr和lr_up都是4维的大小,格式应该是(batch_size, channel, height, width)。
具体修改示例:
在转换为Tensor后,给
lr和lr_up补全channel维度,再扩batch维: - User
- Assistant
- User
i_mean和i_std是用来干嘛的》
- Assistant
i_mean和i_std在你的代码中,是用来对输入的 RGB 图像进行标准化处理的。
背景:
深度学习模型尤其是卷积神经网络,通常在训练时会对输入图像进行**归一化(Normalization)**处理,使输入数据均值接近0,方差接近1,这样有助于加快模型收敛,提高模型训练稳定性和性能。
具体作用:
i_mean = np.array([0.20869005, 0.20350389, 0.19058013]).reshape(3, 1, 1)i_std = np.array([0.07024252, 0.06237046, 0.06703659]).reshape(3, 1, 1)
表示对 三个通道(R, G, B) 的均值和标准差,形状
(3,1,1)可以直接跟形状为(3, H, W)的图像做广播计算。你的代码是这样标准化 RGB 图像:
rgb = rgb / 255.0 # 先归一化到 [0,1] rgb = (rgb - i_mean) / i_std # 标准化:减去均值,除以标准差相当于对每个通道执行:
[ \text{rgb}[c,:,:] \leftarrow \frac{\text{rgb}[c,:,:] - \text{i_mean}[c]}{\text{i_std}[c]} ]
为什么这么做?
- 训练的时候模型是基于这种均值为0、方差为1的分布,这样输入数据分布和训练时一致,能保证推理效果。
- 不做标准化,输入数据范围和训练时不匹配,模型预测可能变差。
总结
i_mean:RGB每个通道的均值i_std:RGB每个通道的标准差- 用它们对归一化后的RGB做标准化处理,保证输入数据分布和训练时一致
这是一种典型的图像预处理步骤,很多经典网络(如ResNet)都用过类似预处理。
- User
我不希望用到这两个值,请帮我去掉
- Assistant
如果你不想使用
i_mean和i_std做标准化处理,可以直接去掉相关代码部分,改为对RGB图像只做简单的归一化(将像素值从[0, 255]缩放到[0, 1]),代码调整如下:
修改前:
rgb = rgb / 255.0 rgb = (rgb - i_mean) / i_std修改后:
rgb = rgb / 255.0 # 去掉减均值和除以标准差操作
修改后的完整代码片段示例:
# 读取和预处理后的rgb rgb = rgb.astype(np.float32) / 255.0 # 不执行标准化,直接用归一化的rgb输入模型
你代码中找到对应位置,改成这样即可,示例如下:
dep, rgb = mod_crop(np.expand_dims(dep, 0), rgb.transpose(2, 0, 1), modulo=32) rgb = rgb.astype(np.float32) / 255.0 # 只做简单归一化 # 去掉以下标准化代码 # i_mean = np.array([0.20869005, 0.20350389, 0.19058013]).reshape(3, 1, 1) # i_std = np.array([0.07024252, 0.06237046, 0.06703659]).reshape(3, 1, 1) # rgb = (rgb - i_mean) / i_std
注意
- 去掉标准化后,你的推理数据分布和训练时不一致,可能会导致模型效果下降,这需要你自行评估。
- 如果模型训练时未做过标准化,那去掉没问题。
- 最好确认你的训练代码是否使用了该均值和方差。
如果你需要我帮你给整段代码做去标准化的示范,也可以告诉我!
- User
请注意,输入的图像既有uint8也有uint16格式的,归一化是否需要修改
- Assistant
你说得非常对,输入图像包含**uint8(0-255)和uint16(0-65535)**两种格式时,归一化需要区别对待,否则直接除以255可能导致归一化错误。
归一化处理建议
1. 判断图像数据类型再归一化
- uint8 图像,像素范围是 0~255,归一化就除以 255
- uint16 图像,像素范围是 0~65535,归一化应除以 65535 或实际最大值
2. 代码示范
def normalize_img(img): """ 归一化图像到[0,1]浮点数,兼顾uint8和uint16输入 """ if img.dtype == np.uint8: return img.astype(np.float32) / 255.0 elif img.dtype == np.uint16: # 也可以用 img.max() 动态归一化,但最好知道最大值 max_val = 65535.0 return img.astype(np.float32) / max_val else: # 如果是float类型,假设已归一化,直接返回 return img.astype(np.float32) # 使用示例: rgb = normalize_img(rgb) dep = normalize_img(dep) lr = normalize_img(lr)
3. 在你的代码中替换:
# 原代码 # rgb = rgb.astype(np.float32) / 255.0 # dep = dep.astype(np.float32) # 注意后面除 255 的操作 # 修改为 rgb = normalize_img(rgb) dep = normalize_img(dep) lr = normalize_img(lr) # 低分辨率图也归一化
4. 归一化后不用再乘以255,依旧保证所有输入数据在同一尺度方便模型处理。
总结
- 归一化前判断数据类型,对不同格式采取不同归一化系数
- 这样能兼容 uint8 uint16 图像输入的多样性
- User
quantize是干什么的
- Assistant
quantize函数的作用是将模型输出(通常是浮点数)的像素值映射回量化的像素值范围,通常是[0, 255]之间的整数类型,这样方便保存为图片格式(如 PNG、BMP 等),或者做评价指标计算。
具体来讲:
在深度学习图像超分或者恢复任务中,模型输出通常是归一化的浮点型图像数据,比如范围可能是
[0, 1]或者其他经过归一化的区间。而最终想要:
- 可视化时,要将其转换回
[0, 255]的整数像素值 - 评价指标(如PSNR、RMSE)计算时,也需要整数格式像素或者接近真实图像的数值分布
quantize函数就是完成这个“浮点->像素值量化”的转换。
你的定义:
def quantize(img, rgb_range): pixel_range = 255 / rgb_range return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range)解析:
img是模型输出的tensor,可能范围是[0, rgb_range](例如rgb_range=1时即[0,1])pixel_range = 255 / rgb_range,映射系数,把数字放大到[0, 255]范围,例如如果 ,
- 可视化时,要将其转换回
- User
- Assistant
- User
原本计算rmse的需要保留
- Assistant
- User
out_img_int = np.round(out_img).astype(np.uint8) 这一句具体是怎么起作用的
- Assistant
这句代码:
out_img_int = np.round(out_img).astype(np.uint8)的作用是:
1.
np.round(out_img)将
out_img中的每个浮点数元素四舍五入为最接近的整数。- 例如,数值
123.4会变成123,123.6会变成124。 - 它返回的是浮点数,但数值已经是整数形式(如 0.0,1.0,2.0 等)。
2.
.astype(np.uint8)将四舍五入后的浮点数数组转换成无符号8位整数型数组(uint8)。
- 数据会被转成 0 到 255 之间的整数
- 这是通常用于存储或显示的图像类型,例如常见的灰度图或彩色图像通道数据
综合说明
- 你的模型输出的
out_img是经过反归一化的浮点数图像,数值可能是0到255之间的浮点。 - 直接将浮点图像保存为uint8格式前,先需要做四舍五入,避免截断带来的误差(会影响图像质量)。
- 转成
uint8后,就是一张标准的8位图像,可以用OpenCV或其他图像库保存或显示。
举个简单例子
import numpy as np out_img = np.array([[12.6, 45.2], [200.7, 254.9]]) print("原始浮点数组:") print(out_img) rounded = np.round(out_img) print("四舍五入后:") print(rounded) uint8_img = rounded.astype(np.uint8) print("转换为uint8数组:") print(uint8_img) - 例如,数值
- User
帮我在代码中加一个打印,打印输入图像的格式和输出sr图像的格式
- Assistant
你可以在主循环里加载图像后和保存输出前,分别加打印输入图像格式和输出图像格式的代码。修改示例如下:
for prefix, files in groups.items(): if not {'depth', 'depth_x4', 'rgb'}.issubset(files.keys()): print(f'Warning: missing files for {prefix}, skipped.') continue dep = cv2.imread(files['depth'], cv2.IMREAD_UNCHANGED) lr = cv2.imread(files['depth_x4'], cv2.IMREAD_UNCHANGED) rgb = cv2.imread(files['rgb'], cv2.IMREAD_COLOR) if dep is None or lr is None or rgb is None: print(f'Failed loading images for {prefix}') continue # 打印输入深度图格式 print(f"{prefix}: Input dep dtype = {dep.dtype}, shape = {dep.shape}") rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) # 其余归一化及模型推理代码 # 反归一化后 out_img = out.squeeze().cpu().numpy() out_img = np.clip(out_img, 0, 1) * dep_max # 转为对应整数格式 if dep.dtype == np.uint8: out_img_int = np.round(out_img).astype(np.uint8) elif dep.dtype == np.uint16: out_img_int = np.round(out_img).astype(np.uint16) else: out_img_int = out_img.astype(np.float32) # 打印输出图像格式 print(f"{prefix}: Output SR image dtype = {out_img_int.dtype}, shape = {out_img_int.shape}") # 保存图像操作... - User
报错 Traceback (most recent call last): File "test2.py", line 185, in main() File "test2.py", line 158, in main out = model(inputs)['img_out'] File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 363, in forward tmp = self.fuse_conv[i](depth=depth_out[3 - i], File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 292, in forward depth, guide = self.attention_layer(depth=depth, guidance=guide) File "/home/jianruobing/anaconda3/envs/UHDFour/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "/home/jianruobing/code/AHMF-main/AHMF-test/ahmf.py", line 272, in forward fuse_feature = self.squeeze(torch.cat((depth, guidance), 1)) RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 32 but got size 48 for tensor number 1 in the list.
- Assistant
这个报错信息:
RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 32 but got size 48 for tensor number 1 in the list.出现在:
fuse_feature = self.squeeze(torch.cat((depth, guidance), 1))说明
depth和guidance在除维度1(channel)外的某个维度上尺寸不匹配,比如高或宽。 - User
depth.shape=torch.Size([1, 64, 32, 128]), guidance.shape=torch.Size([1, 64, 48, 128])
- Assistant
从你给出的打印信息:
depth.shape=torch.Size([1, 64, 32, 128]) guidance.shape=torch.Size([1, 64, 48, 128])可以看到:
- 两个张量的 batch 和 channel 维度是一致的(都是1和64)
- 它们在高度维度 (第3维) 不一致,分别是 32 和 48
- 宽度维度(第4维)是一致的(128)
这也正是拼接时报错的原因:
torch.cat((depth, guidance), 1)要求除了维度1(channel)之外,其他维度都相同,但这里高度维大小不一样,导致无法拼接。
解决方案思路