Python:未定义全局名称或在分配之前引用对象

时间:2015-03-05 16:46:47

标签: python

我试图使用numpy和pydicom制作3D图像堆栈,以便用ITK进行过滤。但是,我无法让堆叠器功能返回堆叠的图像。

如果我删除全局变量声明,我得到一个错误,说我在定义之前引用了imstack。如果我将变量声明为全局变量,则会收到错误消息,指出全局名称未定义。 Catch 22的排序...不完全确定我应该做什么,而且我知道全局变量非常邪恶,所以如果我不必使用它们,我就不喜欢。

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

2 个答案:

答案 0 :(得分:1)

你根本不需要全局...但我不认为这个错误是你唯一的问题...我认为你有这个脚本的基本逻辑问题

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路径:
只是我们/它适用于python中的所有操作系统并且不需要rawstrings或escapes但是path=r"C:\test"path = "C:\\test"path="C:/test"都将正常运行,path="C:\test"将不是

答案 1 :(得分:-1)

看起来整个函数应该缩进。

在定义你的功能之前。

imstack = None
slope = None
intercept = None