【问题标题】:local variable 'nheigth' referenced before assignment on python在 python 上赋值之前引用的局部变量“nheigth”
【发布时间】:2018-04-11 06:50:43
【问题描述】:

我正在运行以下 python 函数:

def imageprepare(argv):

    im = Image.open(argv).convert('L')
    width = float(im.size[0])
    height = float(im.size[1])
    newImage = Image.new('L', (28, 28), (255)) 

    if width > height: 
        nheight = int(round((20.0/width*height),0))
        if (nheigth == 0):
            nheigth = 1  
        img = im.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wtop = int(round(((28 - nheight)/2),0))
        newImage.paste(img, (4, wtop))
    else:
        nwidth = int(round((20.0/height*width),0)) #
        if (nwidth == 0):
            nwidth = 1
        img = im.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wleft = int(round(((28 - nwidth)/2),0))
        newImage.paste(img, (wleft, 4))

    tv = list(newImage.getdata())

    tva = [ (255-x)*1.0/255.0 for x in tv] 
    return tva

它给出了错误:

UnboundLocalError:在赋值之前引用了局部变量“nheigth”。

我在 conda 环境中运行它并使用 python 3.6。

请帮助我。我是 python 新手。

【问题讨论】:

    标签: python-3.x conda


    【解决方案1】:

    正如@Falko 已经发现的那样,您在声明为nheight 然后使用nheigth 的变量中有错字。

    Python 是一种动态语言,没有强制声明变量,如果没有适当的工具,在运行前不容易发现这种错误。

    我建议您使用合适的 Python IDE,例如 PyCharm,它会在您键入时为您发现这些错误。

    【讨论】:

      【解决方案2】:

      有一个错字:nheigth vs. nheight

      【讨论】:

        猜你喜欢
        • 2013-07-04
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 2021-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多