0

我正在尝试创建一个用于查看和分析 DICOM 切片的应用程序。我已经在 MATLAB 中完成了这个应用程序,但是 MATLAB 没有足够的工具来构建一个非常好的 GUI,而且 3D 图片很糟糕。所以,我很长一段时间都在尝试使用 ITK 和 VTK 在 Xcode 中构建一个应用程序,但没有任何成功。有一天我发现 xcodeproject PythonDicomDocument - 这个项目(用 python 编写)可以读取和显示 DICOM 图像!我已经阅读了关于 python 和 cocoa 的教程,但我仍然无法理解这个项目是如何工作的——它有文件PythonDicomDocumentDocument.py:

from Foundation import *
from AppKit import *
from iiDicom import *

import objc


import dicom
import numpy
import Image


class PythonDicomDocumentDocument(NSDocument):
imageView = objc.IBOutlet('imageView')

def init(self):

    self = super(PythonDicomDocumentDocument, self).init()
    self.image = None
    return self

def windowNibName(self):

    return u"PythonDicomDocumentDocument"

def windowControllerDidLoadNib_(self, aController):
    super(PythonDicomDocumentDocument, self).windowControllerDidLoadNib_(aController)
    if self.image:
        self.imageView.setImageScaling_(NSScaleToFit)
        self.imageView.setImage_(self.image)


def dataOfType_error_(self, typeName, outError):
    return None

def readFromData_ofType_error_(self, data, typeName, outError):
    return NO

def readFromURL_ofType_error_(self, absoluteURL, typeName, outError):
    if absoluteURL.isFileURL():
        slice = iiDcmSlice.alloc().initWithDicomFileSlice_(absoluteURL.path())

        dicomImage = slice.sliceAsNSImage_context_(True, None)

        if dicomImage:
            self.image = dicomImage
                            #self.image = dicomImage

            return True, None

    return False, None

文件 main.m:

**#import "<"Python/Python.h>**

**#import "<"Cocoa/Cocoa.h>**


int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *resourcePath = [mainBundle resourcePath];
    NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath,               [resourcePath stringByAppendingPathComponent:@"PyObjC"],      @"/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/", nil];

setenv("PYTHONPATH", [[pythonPathArray componentsJoinedByString:@":"] UTF8String], 1);

    NSArray *possibleMainExtensions = [NSArray arrayWithObjects: @"py", @"pyc",            @"pyo", nil];
    NSString *mainFilePath = nil;

for (NSString *possibleMainExtension in possibleMainExtensions) {
    mainFilePath = [mainBundle pathForResource: @"main" ofType: possibleMainExtension];
    if ( mainFilePath != nil ) break;
}

if ( !mainFilePath ) {
    [NSException raise: NSInternalInconsistencyException format: @"%s:%d main() Failed to find the Main.{py,pyc,pyo} file in the application wrapper's Resources directory.", __FILE__, __LINE__];
}

Py_SetProgramName("/usr/bin/python");
Py_Initialize();
PySys_SetArgv(argc, (char **)argv);

    const char *mainFilePathPtr = [mainFilePath UTF8String];

    FILE *mainFile = fopen(mainFilePathPtr, "r");



int result = PyRun_SimpleFile(mainFile, (char *)[[mainFilePath lastPathComponent] UTF8String]);



if ( result != 0 )
    [NSException raise: NSInternalInconsistencyException
                format: @"%s:%d main() PyRun_SimpleFile failed with file '%@'.  See console for errors.", __FILE__, __LINE__, mainFilePath];

[pool drain];

return result;

}

所以我想“翻译”阅读.dcm的MATLAB代码:

directory = uigetdir; % after this command Finder window will appear and user will             choose a folder with .dcm files

fileFolder = directory; % the path to the folder is saved to a variable fileFolder
dirOutput = dir(fullfile(fileFolder,'*.dcm')); % choose files .dcm in specified folder     %and save their names 
fileNames = {dirOutput.name}';

Names = char(fileNames);
numFrames = numel(fileNames); % count the number of files in the folder


    for i = 1:numFrames
    Volume(:,:,i) = dicomread(fullfile(fileFolder,Names(i,:))); % create a 3D array of         %DICOM pixel data
    end;

谁能告诉我如何运行相同的代码来使用 python 在 Xcode 中读取 .dcm 文件?

我听说 python 和 MATLAB 很相似。

4

1 回答 1

1

恭喜您选择 Python 与 DICOM 合作;根据我的经验, SciPy /numpy/matplotlib 家族在处理大量数据方面比 MATLAB(或至少 GNU Octave)要好得多

使用GDCM的 python 绑定、来自 GDCM 示例的 ConvertNumpy.py 和matplotlib加载和显示代码:

#!/usr/bin/env python

import gdcm
import ConvertNumpy
import numpy as np
import matplotlib.pyplot as plt

def loadDicomImage(filename):
    reader=gdcm.ImageReader()
    reader.SetFileName(filename)
    reader.Read()
    gdcmimage=reader.GetImage()
    return ConvertNumpy.gdcm_to_numpy(gdcmimage)

image=loadDicomImage('mydicomfile.dcm')

plt.gray()
plt.imshow(image)
plt.show()

请注意,如果您的 DICOM 数据包含明显超出图像的空气骨骼范围的“填充”值,则可能会混淆 imshow 的自动缩放;对该调用使用 vmax,vmin 参数来指定您实际想要查看的范围,或实现您自己的窗口调平代码(这在 numpy 中是微不足道的)。

于 2011-09-17T08:49:15.527 回答