ITK+VTK+Python的整合及例子程序

配置: VS2008(32-bit)

Python2.7.8(32-bit)

Cmake 3.0

ITK4.5.2

VTK 版本要求5.9及其以上

注意: 和Python结合建议使用VS2008,在VS2010中有可能编译不通过,博主经过多次试验发现在VS2010中总是报错。 

一,前期准备

1.1 安装VS2008

1.2 安装Cmake

1.3 安装Python2.7.8

1.4 安装VTK 5.10(方法见之前的一篇博文)

1.5 下载pygccxml并安装:下载好以后使用Python 命令运行pygccxml文件夹中的setup.py文件。

1.6 下载ITK源码

新建一个目录#ITK_SOUCCE#,将itk下载到该目录下并且解压到当前文件夹。例如,如果#ITK_SOUCCE#=D:\ITK_source,那么解压后ITK的源文件放在了这个目录下面:D:\ITK_source\InsightToolkit-4.5.2

1.7 新建两个文件夹

存放cmake产生的ITK项目文件#SOLUTION_PATH#

存放编译成功后的bin,libinclude等文件#BUILD_OUTPUT#

例如,我的设置是#SOLUTION_PATH#=C:\IVTK\ITK32Py_install

#BUILD_OUTPUT# =C:\IVTK\ITK32Py

二,Cmake中的设置

where is the source code 选择#ITK_SOUCCE#/InsightToolkit-4.5.2

where to build the binaries 选择#SOLUTION_PATH#

编译器选择VS 2008

等待Configure完成。

cmake的选项中将BUILDTESTING和BUILD EXAMPLES不选。

勾选BUILD_SHARED_LIBS.

勾选Advanced之后更改CMAKE_INSTALL_PREFIX(表示编译ITK后生成的lib 及include等的安装路径)设置为#BUILD_OUTPUT#

勾选ITKV3_COMPATIBILITY

勾选 ITK_WRAP_PYTHON

勾选 Module_ITKVtkGlue

检查VTK_DIR是否正确,例如C:/IVTK/VTK510_32Py/lib/vtk-5.10

再次点击 Configure, 直至所有条目都变成灰色,表示配置成功, 点击Generate确认。

三,使用VS2008编译

3.1 设置环境变量

gccxml_pah=#SOLUTION_PATH#\Wrapping\Generators\GccXML\gccxml\bin

%gccxml_path%添加到path环境变量的末尾

3.2   编译

VS2008打开位于#SOLUTION_PATH#下面的ITK项目文件,选择Release进行编译。

3.3 安装

编译成功后再次编译INSTALL工程,相关的include, lib和bin文件就被提取到了#BUILD_OUTPUT#目录下。

四,后续

4.1 #BUILD_OUTPUT#\bin中的dll文件复制到:#BUILD_OUTPUT#\ lib\ITK-4.5\Python

4.2#BUILD_OUTPUT#\lib\ITK-4.5\Python路径添加到EclipsePYTHONPATH

五,例子程序

5.1 用ITK打开并保存一副图像

import itk
import sys
import vtk

inputfilename="D:/DATA/small/0200.dcm"
outputfilename="D:/DATA/0200.png"
#
# Reads a 2D image in with signed short (16bits/pixel) pixel type
# and save it as unsigned char (8bits/pixel) pixel type
#
InputImageType  = itk.Image.SS2
OutputImageType = itk.Image.UC2

reader = itk.ImageFileReader[InputImageType].New()
writer = itk.ImageFileWriter[OutputImageType].New()


filter = itk.RescaleIntensityImageFilter[InputImageType, OutputImageType].New()
filter.SetOutputMinimum( 0 )
filter.SetOutputMaximum(255)

filter.SetInput( reader.GetOutput() )
writer.SetInput( filter.GetOutput() )

reader.SetFileName(inputfilename )
writer.SetFileName(outputfilename )

writer.Update()

5.2 用ITK打开图像,用VTK显示

在上述代码后面添加:

ivfilter=itk.ImageToVTKImageFilter[OutputImageType].New()
ivfilter.SetInput(filter.GetOutput())
viewer=vtk.vtkImageViewer()
iren=vtk.vtkRenderWindowInteractor()
viewer.SetupInteractor(iren)
viewer.SetInput(ivfilter.GetOutput())
viewer.Render()
viewer.SetColorWindow(255)
viewer.SetColorLevel(128)
iren.Start()

5.3 ITK 配准的例子

from InsightToolkit import *
from sys import argv

fixedImageName="D:/DATA/Brain.png"
movingImageName="D:/DATA/Brainshifted13x17y.png"
outputImageName="D:/DATA/Brainresult2.png"

fixedImageReader  = itkImageFileReaderIF2_New()
movingImageReader = itkImageFileReaderIF2_New()

fixedImageReader.SetFileName(  fixedImageName )
movingImageReader.SetFileName( movingImageName )

fixedImageReader.Update()
movingImageReader.Update()

fixedImage  = fixedImageReader.GetOutput()
movingImage = movingImageReader.GetOutput()

#
#  Instantiate the classes for the registration framework
#
registration = itkImageRegistrationMethodIF2IF2_New()
imageMetric  = itkMeanSquaresImageToImageMetricIF2IF2_New()
transform    = itkTranslationTransformD2_New()
optimizer    = itkRegularStepGradientDescentOptimizer_New()
interpolator = itkLinearInterpolateImageFunctionIF2D_New()


registration.SetOptimizer(    optimizer.GetPointer()    )
registration.SetTransform(    transform.GetPointer()    )
registration.SetInterpolator( interpolator.GetPointer() )
registration.SetMetric(       imageMetric.GetPointer()  )
registration.SetFixedImage(  fixedImage  )
registration.SetMovingImage( movingImage )

registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() )

transform.SetIdentity()
initialParameters = transform.GetParameters()

registration.SetInitialTransformParameters( initialParameters )

#
# Iteration Observer
#
def iterationUpdate():
    currentParameter = transform.GetParameters()
    print "M: %f   P: %f %f " % ( optimizer.GetValue(),
                        currentParameter.GetElement(0),
                        currentParameter.GetElement(1) )

iterationCommand = itkPyCommand_New()
iterationCommand.SetCommandCallable( iterationUpdate )
optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() )



#
#  Define optimizer parameters
#
optimizer.SetMaximumStepLength(  4.00 )
optimizer.SetMinimumStepLength(  0.01 )
optimizer.SetNumberOfIterations( 200  )


print "Starting registration"

#
#  Start the registration process
#

registration.Update()


#
# Get the final parameters of the transformation
#
finalParameters = registration.GetLastTransformParameters()

print "Final Registration Parameters "
print "Translation X =  %f" % (finalParameters.GetElement(0),)
print "Translation Y =  %f" % (finalParameters.GetElement(1),)

#
# Now, we use the final transform for resampling the
# moving image.
#
resampler = itkResampleImageFilterIF2IF2_New()
resampler.SetTransform( transform.GetPointer()    )
resampler.SetInput(     movingImage  )

region = fixedImage.GetLargestPossibleRegion()

resampler.SetSize( region.GetSize() )

resampler.SetOutputSpacing( fixedImage.GetSpacing() )
resampler.SetOutputOrigin(  fixedImage.GetOrigin()  )
resampler.SetOutputDirection(  fixedImage.GetDirection()  )
resampler.SetDefaultPixelValue( 100 )

outputCast = itkRescaleIntensityImageFilterIF2IUC2_New()
outputCast.SetOutputMinimum(      0  )
outputCast.SetOutputMaximum(  255  )
outputCast.SetInput(resampler.GetOutput())

#
#  Write the resampled image
#
writer = itkImageFileWriterIUC2_New()

writer.SetFileName( outputImageName )
writer.SetInput( outputCast.GetOutput() )
writer.Update()
print "image registration has been finished"

注意:运行该例子,在Observer的定义处可能会报错:

iterationCommand = itkPyCommand_New()

NameError: name 'itkPyCommand_New' is notdefined

找到InsightToolkit.py文件(#BUILD_OUTPUT#\lib\ITK-4.5\Python下面),在最后一行添加添加from ITKPyUtilsPython import *,再次运行该例子程序。

接下来会遇到一个新的错误:

Traceback (most recent call last):

 File"C:\Users\User\workspace\python_itk\registration2D.py", line 83, in

   optimizer.AddObserver( itkIterationEvent(),iterationCommand.GetPointer() )

 File "C:\IVTK\ITK32Py\lib\ITK-4.5\Python\ITKCommonBasePython.py",line 1464, in AddObserver

   elif len(args) == 2 and not issubclass(args[1].__class__, itk.Command)and callable(args[1]):

 File"C:\IVTK\ITK32Py\lib\ITK-4.5\Python\itkLazy.py", line 37, in__getattribute__

   itkBase.LoadModule(module, namespace)

 File"C:\IVTK\ITK32Py\lib\ITK-4.5\Python\itkBase.py", line 119, inLoadModule

   for k, v in module.__dict__.items():

UnboundLocalError: local variable 'module'referenced before assignment

  解决办法:在itkBase.py中(#BUILD_OUTPUT#\lib\ITK-4.5\Python下面),103行后面添加如下代码:

 module = loader.load(swigModuleName)

  再次运行该例子程序,即可成功。



你可能感兴趣的:(其它,图像处理)