开发者

How to read .dcm in Xcode using python?

开发者 https://www.devze.com 2023-03-30 05:41 出处:网络
I\'m trying to create an app for viewing and analyzing DICOM slices. I have done this app in MATLAB, but MATLAB does not have enough tools to build a really nice GUI and 3D picture is bad. So, I was t

I'm trying to create an app for viewing and analyzing DICOM slices. I have done this app in MATLAB, but MATLAB does not have enough tools to build a really nice GUI and 3D picture is bad. So, I was trying to use ITK and VTK to build an app in Xcode for a long period of time but without any success. One day I found xcodeproject PythonDicomDocument - this project (written in python) can read and show DICOM image! I have read a tutorial about python and cocoa but I still can't understand how this project works - it has file 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('im开发者_如何学编程ageView')

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

and file 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;

}

So I want to "translate" MATLAB code for reading .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;

Could anyone please tell me how to run the same code for reading .dcm files in Xcode using python???

I've heard that python and MATLAB are similar.


Congratulations on choosing Python for working with DICOM; the SciPy/numpy/matplotlib clan is much better at dealing with huge amounts of volume data than MATLAB (or at least GNU Octave) in my experience.

Trivia load and display code using GDCM's python bindings, a ConvertNumpy.py from GDCM's examples and 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()

Note that If your DICOM data contains "padding" values significantly outside your image's air-bone range it might confuse imshow's auto-scaling; use vmax,vmin parameters to that call to specify the range you actually want to see, or implement your own window-levelling code (which is trivial in numpy).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号