Python:赋值前未定义全局名称或引用对象

Python:赋值前未定义全局名称或引用对象,python,Python,我正在尝试使用numpy和pydicom制作一个3D图像堆栈,以便使用ITK进行过滤。不过,我在让堆叠器函数返回堆叠的图像时遇到了问题 如果我删除全局变量声明,我会得到一个错误,说我在定义imstack之前引用了它。如果我将变量声明为全局变量,则会出现一个错误,表明未定义全局名称。有点像陷阱22。。。我不太确定我应该怎么做,我知道globals是非常邪恶的,所以如果我不需要使用它们,我不想使用 def imgstacker(path): import os import dic

我正在尝试使用numpy和pydicom制作一个3D图像堆栈,以便使用ITK进行过滤。不过,我在让堆叠器函数返回堆叠的图像时遇到了问题

如果我删除全局变量声明,我会得到一个错误,说我在定义imstack之前引用了它。如果我将变量声明为全局变量,则会出现一个错误,表明未定义全局名称。有点像陷阱22。。。我不太确定我应该怎么做,我知道globals是非常邪恶的,所以如果我不需要使用它们,我不想使用

def imgstacker(path):

    import os
    import dicom as dcm
    import numpy as np

    global imstack
    global slope
    global intercept

    for path, dirs, files in os.walk(path):
        zlen = len(files)
        sizer = dcm.read_file(path+files[0],force=True)
        slope = sizer.RescaleSlope
        intercept = sizer.RescaleIntercept
        xlen = sizer.pixel_array.shape[0]
        ylen = sizer.pixel_array.shape[1]
        del sizer
        imstack = np.empty((zlen,xlen,ylen),dtype=np.int16)

        for i in range(0,zlen):
            print ('Reading: ' + path + files[i])
            img_raw = dcm.read_file(path + files[i],force=True)
            img = img_raw.pixel_array
            imstack[i,:,:] = img

    return imstack, slope, intercept
运行此模块的主脚本中的代码是:

imstack, slope, intercept = imgstacker('/my/favorite/directory')
如果删除全局定义,则回溯为:

 UnboundLocalError Traceback (most recent call last) 
 K:\dir\main.py in <module>() 6 import matplotlib.cm as cm 
 imstack, slope, intercept = imgstacker('my/favorite/directory\\')
 out = temp_test(imstack*slope + intercept) 
 K:\dir\imgstacker.py in imgstacker(path)
 intercept = img_raw.RescaleIntercept 
 return imstack, slope, intercept 
 UnboundLocalError: local variable 'imstack' referenced before assignment
UnboundLocalError回溯(最近一次调用)
K:\dir\main.py in()6将matplotlib.cm导入为cm
imstack,slope,intercept=imgstacker('my/favorite/directory\\\')
out=温度测试(imstack*斜率+截距)
imgstacker(路径)中的K:\dir\imgstacker.py
截距=img_原始重缩放截距
返回堆栈、斜率、截距
UnboundLocalError:赋值前引用的局部变量“imstack”

看起来整个函数应该缩进

在定义函数之前

imstack = None
slope = None
intercept = None

你根本就不需要地球仪。。。但我不认为这个错误是你唯一的问题。。。我认为这个脚本有一些基本的逻辑问题

def imgstacker(path):

    import os
    import dicom as dcm
    import numpy as np

    for path, dirs, files in os.walk(path):
        zlen = len(files)
        sizer = dcm.read_file(path+files[0],force=True)
        xlen = sizer.pixel_array.shape[0]
        ylen = sizer.pixel_array.shape[1]
        del sizer
        imstack = np.empty((zlen,xlen,ylen),dtype=np.int16)

        for i in range(0,zlen):
            print ('Reading: ' + path + files[i])
            img_raw = dcm.read_file(path + files[i],force=True)
            img = img_raw.pixel_array
            imstack[i,:,:] = img
            slope = img_raw.RescaleSlope
            intercept = img_raw.RescaleIntercept
    #: the ONLY way these are undefined is if you do not enter the loops above
    return imstack, slope, intercept

imstack, slope, intercept = imgstacker('/my/favorite/directory')\
实际问题似乎是正确地脱离了路径 WRT路径:

仅限us/适用于python中的所有操作系统,不需要原始字符串或转义符,但无论是
path=r“C:\test”
还是
path=“C:\\test”
还是
path=“C:/test”
都将正常运行,
path=“C:\test”
将不会

而不是
全局imstack
尝试
imstack=None
@Tim Casteljins TypeError:“NoneType”对象不可编辑我正在迭代imstack并每次添加一个新的“层”。我认为这不合适。请先检查目录是否存在。
os.walk
可能不遍历任何项,在这种情况下,当您到达
return
时,没有一个变量被定义。如果在使用前用iterable替换掉,那么没有一个变量是不iterable也没关系。@Kevin目录确实存在,我已经进入python并手工编写了同样多的代码。我只是想“自动化”这个过程,因为用手迭代地将图像添加到一个大堆栈中会给我带来腕管综合症。这不是一个真正的答案,几乎肯定不会解决他的问题。我无法将其格式正确设置,但在我的文本编辑器中已正确缩进。请参阅对原始问题的评论,这对我不起作用。在全局范围的最后一行之前添加这三行将删除使用前引用的内容。此时可以删除全局行。@RobertJacobs它删除一个错误并用另一个错误替换它。我对最初的问题进行了评论,并给出了确切的错误以及我认为发生了什么。我不确定您在这里做了什么来更改我的代码。按照您的方式,我得到了我描述的第二个错误:赋值前引用。也许我看这段代码太久了,看不出明显的原因?我错在这里的逻辑是什么?请把完整的回溯。。。这不可能给你你描述的错误。。。由于它不是一个可运行的示例,我无法运行它来验证解决方案…您有一个返回,但您正在多次覆盖imstack。。。然后覆盖坡度和截距(重复)。。。除了路径中的最后一个文件之外,其他所有文件都被完全忽略,它只返回它查看的最后一个文件的数据{-------------------------------------------------------------------UnboundLocalError Traceback(最近一次调用last)K:\dir\main.py in()6导入matplotlib.cm作为cm 7--->8 imstack,slope,intercept=imgstacker('my/favorite/directory\\')9 out=temp_测试(imstack*slope+intercept)10 K:\dir\imgstacker.py在imgstacker(路径)中21 intercept=img_raw.RescaleIntercept 22-->23返回imstack,slope,intercept UnboundLocalError:赋值前引用的局部变量“imstack”}我很抱歉这有多可怕,我不确定如何干净地复制cmd.exe ipython输出。。。