如何将不返回任何特定值的函数组合到一个类中

2024-09-23 06:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

以下两个函数在目录中读取和保存图像:

def resample(image, reference_image, def_value=0.0):
    return sitk.Resample(image,
                         reference_image,
                         sitk.Transform(),
                         sitk.sitkLinear,
                         def_value,
                         reference_image.GetPixelID())

def ResampleNiiSave(dcmPath, nrdPath):
    dcmItk = dicomread(dcmPath, imgitk=True) # contains one file multiple slice
    nrdItk = nrrdread(nrdPath, imgitk=True) # contains single nrrd file
    data = [dcmItk, None]
    if len(nrdItk.GetSize()) == 4:
        if nrdItk.GetSize()[3] == 3:
            for ig in range(3):
                imgnp = sitk.GetArrayFromImage(nrdItk)[ig, ...]
                imgItk = sitk.GetImageFromArray(imgnp)
                data[1] = imgItk
                nrdItkAl = resample(data[1], data[0])
                nrd2niiPath = os.path.splitext(nrdPath)[0]+'_{}'.format(ig)+'.nii.gz'
                if os.path.isfile(nrd2niiPath) is None:
                    sitk.WriteImage(nrdItkAl, nrd2niiPath)
                del imgnp, imgItk  # necessary?
        elif nrdItk.GetSize()[3] == 1:
            imgnp = sitk.GetArrayFromImage(nrdItk)
            imgnp = np.squeeze(imgnp)
            imgItk = sitk.GetImageFromArray(imgnp)
            data[1] = imgItk
            nrdItkAl = resample(data[1], data[0])
            nrd2niiPath = os.path.splitext(nrdPath)[0] + '.nii.gz'
            if os.path.isfile(nrd2niiPath) is None:
                sitk.WriteImage(nrdItkAl, nrd2niiPath)
            del imgnp, imgItk
        else:
            raise ValueError("image has unknown dimension")
    else:
        data[1] = nrdItk
        nrdItkAl = sitk.Resample(data[1], data[0], sitk.Transform(), sitk.sitkLinear,
                                 np.min(sitk.GetArrayFromImage(data[1])).astype('double'), data[1].GetPixelID())
        nrd2niiPath = os.path.splitext(nrdPath)[0] + '.nii.gz'
        if os.path.isfile(nrd2niiPath) is None:
            sitk.WriteImage(nrdItkAl, nrd2niiPath)
    dcm2niiPath = dcmPath+'.nii.gz'
    if os.path.isfile(dcm2niiPath) is None:
        sitk.WriteImage(dcmItk, dcm2niiPath)

ResampleNiiSave函数不一定返回任何值,而是执行对齐并将变量保存为另一种格式

如何创建一个类来将这两个函数组合为类方法。我尝试了以下方法,但运气不佳:

class prepSeg:
    def __init__(self, dcmPath, nrdPath):
        self.dcmPath = dcmPath
        self.nrdPath = nrdPath

    def resample(self, image, reference_image, def_value=0.0):
        return sitk.Resample(image,
                             reference_image,
                             sitk.Transform(),
                             sitk.sitkLinear,
                             def_value,
                             reference_image.GetPixelID())

    def ResampleNiiSave(self):
        dcmItk = dicomread(self.dcmPath, imgitk=True) # contains one file multiple slice
        nrdItk = nrrdread(self.nrdPath, imgitk=True) # contains single nrrd file
        data = [dcmItk, None]
        if len(nrdItk.GetSize()) == 4:
            if nrdItk.GetSize()[3] == 3:
                for ig in range(3):
                    imgnp = sitk.GetArrayFromImage(nrdItk)[ig, ...]
                    imgItk = sitk.GetImageFromArray(imgnp)
                    data[1] = imgItk
                    nrdItkAl = self.resample(data[1], data[0])
                    nrd2niiPath = os.path.splitext(self.nrdPath)[0]+'_{}'.format(ig)+'.nii.gz'
                    if os.path.isfile(nrd2niiPath) is None:
                        sitk.WriteImage(nrdItkAl, nrd2niiPath)
                    del imgnp, imgItk  # necessary?
            elif nrdItk.GetSize()[3] == 1:
                imgnp = sitk.GetArrayFromImage(nrdItk)
                imgnp = np.squeeze(imgnp)
                imgItk = sitk.GetImageFromArray(imgnp)
                data[1] = imgItk
                nrdItkAl = self.resample(data[1], data[0])
                nrd2niiPath = os.path.splitext(self.nrdPath)[0] + '.nii.gz'
                if os.path.isfile(nrd2niiPath) is None:
                    sitk.WriteImage(nrdItkAl, nrd2niiPath)
                del imgnp, imgItk
            else:
                raise ValueError("image has unknown dimension")
        else:
            data[1] = nrdItk
            nrdItkAl = sitk.Resample(data[1], data[0], sitk.Transform(), sitk.sitkLinear,
                                     np.min(sitk.GetArrayFromImage(data[1])).astype('double'), data[1].GetPixelID())
            nrd2niiPath = os.path.splitext(self.nrdPath)[0] + '.nii.gz'
            if os.path.isfile(nrd2niiPath) is None:
                sitk.WriteImage(nrdItkAl, nrd2niiPath)
        dcm2niiPath = self.dcmPath+'.nii.gz'
        if os.path.isfile(dcm2niiPath) is None:
            sitk.WriteImage(dcmItk, dcm2niiPath)

现在prepSeg类的return应该是什么。但是,我使用两个文件路径输入运行prepSeg,它只是创建类对象,但不执行resamplesave中的任何任务。 例如:

A = prepSeg(dcmFiles[-2],nrdFilesIdx[-2])
# .ResampleNiiSave()
# prepSeg.ResampleNiiSave
print(A)
A.ResampleNiiSave

返回:

prepSeg object at 0x0000025E6D96E710>
<bound method prepSeg.ResampleNiiSave of <prepSeg object at 0x0000025E6D96E710>>

Tags: pathimageselfnonedataifosdef
1条回答
网友
1楼 · 发布于 2024-09-23 06:23:03

好吧,你的IDE搞得一团糟

这是在愚弄你正在发生的事情

请尝试以下代码:

class prepSeg():
    def __init__(self):
        self.a = ''
    def foo(self):
        print(self)
        print(self.a)
        print(self.b)


A = prepSeg()
A.foo()
#prepSeg.foo(prepSeg)

这将产生以下输出:

<__main__.prepSeg object at 0x04267B70>

Traceback (most recent call last):
  File "D:\andrew\Python\soMissingAttribute.py", line 12, in <module>
    A.foo()
  File "D:\andrew\Python\soMissingAttribute.py", line 8, in foo
    print(self.b)
AttributeError: 'prepSeg' object has no attribute 'b'

注意object at 0x...AttributeError的措辞。它也在谈论故意丢失的b

如果我交换驱动程序代码:

A = prepSeg()
#A.foo()
prepSeg.foo(prepSeg)

我得到了不同的输出:

<class '__main__.prepSeg'>
Traceback (most recent call last):
  File "D:\andrew\Python\soMissingAttribute.py", line 13, in <module>
    prepSeg.foo(prepSeg)
  File "D:\andrew\Python\soMissingAttribute.py", line 7, in foo
    print(self.a)
AttributeError: type object 'prepSeg' has no attribute 'a'

现在self打印:<class '__main__.prepSeg'>,并且AttributeError大约是type object 'prepSeg'没有属性a

相关问题 更多 >