gpt4 book ai didi

python - 如何使用python在Xcode中读取.dcm?

转载 作者:行者123 更新时间:2023-12-03 17:36:02 24 4
gpt4 key购买 nike

我正在尝试创建一个用于查看和分析 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;

}

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

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 很相似。

最佳答案

恭喜您选择 Python 来使用 DICOM; SciPy根据我的经验,/numpy/matplotlib clan 在处理大量数据方面比 MATLAB(或至少是 GNU Octave)要好得多。

使用GDCM琐事加载和显示代码的 python 绑定(bind),a ConvertNumpy.py来自 GDCM 的示例和 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 中很简单)。

关于python - 如何使用python在Xcode中读取.dcm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7143638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com