You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报UnboundLocalError:width变量赋值前被引用如何解决

报错信息

代码运行时抛出如下未定义变量错误:

File "C:\Users\Asus\OPIXray-dataset\DOAM\data\OPIXray.py", line 138, in __getitem__
    im, gt, h, w, og_im = self.pull_item(index)
  File "C:\Users\Asus\OPIXray-dataset\DOAM\data\OPIXray.py", line 184, in pull_item
    target = self.target_transform(target, width, height, img_id)
UnboundLocalError: local variable 'width' referenced before assignment
问题根因

报错核心是width、height变量在调用前未完成赋值,由两处逻辑漏洞共同导致:

  • 图片读取逻辑无有效兜底:三次尝试从不同路径读取图片后,如果全部读取失败,img值为None,代码仅打印'wrong'就继续向下执行,没有中断无效流程。
  • 尺寸获取的异常捕获无实质处理:访问None的shape属性会直接抛出异常,此时height/width/channels三个变量完全没有被赋值,但except块仅打印了img_id就放行,后续代码调用这几个变量自然会触发未定义错误。

之前尝试在try-except块后加else分支赋值不生效的原因是:try块内代码执行报错时,else分支的代码根本不会运行,变量依然处于未赋值状态。

修复方案

将pull_item函数替换为如下实现即可:

def pull_item(self, index):
    img_id = self.ids[index]
    target = self._annopath % img_id
    
    # 按优先级遍历路径读取图片,全部读取失败直接抛出明确错误
    img = None
    for path_attr in ['_imgpath', '_imgpath1', '_imgpath2']:
        img_path = getattr(self, path_attr)
        img = cv2.imread(img_path % img_id)
        if img is not None:
            break
    if img is None:
        raise RuntimeError(f"Image read failed, checked all 3 paths, img_id: {img_id}")

    # 前置逻辑已保证img有效,直接读取尺寸即可
    height, width, channels = img.shape
    og_img = img

    try:
        img = cv2.resize(img, (300, 300))
    except:
        raise RuntimeError(f"Image resize failed, img_id: {img_id}")

    if self.target_transform is not None:
        target = self.target_transform(target, width, height, img_id)
    
    return torch.from_numpy(img).permute(2, 0, 1), target, height, width, og_img
修复逻辑说明
  • 重构重复的图片读取代码:用循环遍历三个配置的图片路径,只要读到有效图片就终止读取,所有路径读取失败时直接抛出带img_id的明确错误终止流程,从根源避免None值传入后续步骤。
  • 移除尺寸获取处冗余的try-except:前置逻辑已经保证img是有效读取的图像对象,img.shape可以稳定取值,不会再出现赋值失败的问题。
  • 补全resize操作的异常处理:resize失败时直接抛出错误,避免无效img对象传入后续逻辑引发其他隐蔽问题。

内容的提问来源于stack exchange,提问作者Aakash Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 22:42:19