NameError:全局名称'balanceAr'未定义

时间:2019-10-08 11:18:51

标签: python python-2.7 image-processing

对于以下代码,我收到以下错误(最后一行很重要):

  

警告(来自警告模块):    文件“ C:/ [file_location] / itteration 4.py”,第12行

     

avgNug = reduce(lambda x,y:x + y,eachPix [:3])/ len(eachPix [:3])

     

RuntimeWarning:在ubyte_scalars中遇到溢出

     

回溯(最近通话最近一次):

     

中的文件“ C:/ [file_location] / itteration 4.py”,第45行      

阈值(iar4)

     

文件“ C:/ [file_location] / itteration 4.py”,第13行,阈值

     

balanceAr.append(avgNum)

     

NameError:未定义全局名称“ balanceAr”

我尝试过在其之前编写“ global”,在其定义之外定义它,并为“ global”定义使用多种语法。

该代码来自该代码有效的senddex视频https://www.youtube.com/watch?v=nych18rsXKU

我使用与他相同的Python版本,并且我假设使用相同的库,因为这是播放列表中的第四个程序,而前三个程序运行良好。

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import time

def threshold(imageArray):
balaceAr = []
newAr = imageArray

    for eachRow in imageArray:
        for eachPix in eachRow:
            avgNug = reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3])
            balanceAr.append(avgNum)
    balance = reduce(lambda x, y: x + y, balanceAr)/len(balanceAr)

    for eachRow in newAr:
        for eachPix in eachRow:
            if reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3]) > balance:
                #eachPix 0,1,2,3 = 255
            else:
                #eachPix 0,1,2 = 0
                eachPix[3] = 255

    return newAr

'''in the original code this part is not commented, and there's also a i, i2 and i3
i4 = Image.open('images/sentdex.png')
iar4 = np.array(i4)'''

threshold(iar4)

'''same explanation as previous comment, only coordinates in 2nd () are 0,0;4,0;0,3
fig = plt.figure()
ax4 = plt.subplot2grid((8,6), (4,3), rowspan=4, colspan=3)

ax4.imshow(iar4)
'''

plt.show()

#P.S. I had to write "    " on all lines that didn't have it for stackoverflow
# to interpret it as code, even if it was in the "code" section

2 个答案:

答案 0 :(得分:0)

您在缩放balaceAr = []时遇到语法错误

您可能需要将其更改为balanceAr= []

答案 1 :(得分:0)

在函数定义下方:


balaceAr = [] # <===== Typo

在下次发布前检查拼写错误。