itk中的配准整理

news/2024/11/30 13:40:57/

文章目录

    • Perform 2D Translation Registration With Mean Squares
      • 效果:
      • 源码:
    • 多模态互信息配准 Perform Multi Modality Registration With Viola Wells Mutual Information
      • 效果图
      • 源码:
    • Register Image to Another Using Landmarks 通过标记点配准图像
      • 效果图
      • 源码

Perform 2D Translation Registration With Mean Squares

原文地址: https://examples.itk.org/src/registration/common/perform2dtranslationregistrationwithmeansquares/documentation

效果:

在这里插入图片描述

源码:

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cmimport itk# Perform 2D Translation Registration With Mean Squares
baseDir = r'D:\learn\itk\itk5.3.0\ITK-5.3.0\Examples\Data'
fixed_input_image = baseDir + r"\BrainProtonDensitySlice.png"
moving_input_image = baseDir + r"\BrainProtonDensitySliceShifted13x17y.png"PixelType = itk.ctype("float")
fixedImage = itk.imread(fixed_input_image, PixelType)
movingImage = itk.imread(moving_input_image, PixelType)Dimension = fixedImage.GetImageDimension()
FixedImageType = itk.Image[PixelType, Dimension]
MovingImageType = itk.Image[PixelType, Dimension]TransformType = itk.TranslationTransform[itk.D, Dimension]
initialTransform = TransformType.New()optimizer = itk.RegularStepGradientDescentOptimizerv4.New(LearningRate=4,MinimumStepLength=0.001,RelaxationFactor=0.5,NumberOfIterations=200,
)metric = itk.MeanSquaresImageToImageMetricv4[FixedImageType, MovingImageType].New()registration = itk.ImageRegistrationMethodv4.New(FixedImage=fixedImage,MovingImage=movingImage,Metric=metric,Optimizer=optimizer,InitialTransform=initialTransform,
)movingInitialTransform = TransformType.New()
initialParameters = movingInitialTransform.GetParameters()
initialParameters[0] = 0
initialParameters[1] = 0
movingInitialTransform.SetParameters(initialParameters)
registration.SetMovingInitialTransform(movingInitialTransform)identityTransform = TransformType.New()
identityTransform.SetIdentity()
registration.SetFixedInitialTransform(identityTransform)registration.SetNumberOfLevels(1)
registration.SetSmoothingSigmasPerLevel([0])
registration.SetShrinkFactorsPerLevel([1])
registration.Update()transform = registration.GetTransform()
finalParameters = transform.GetParameters()
translationAlongX = finalParameters.GetElement(0)
translationAlongY = finalParameters.GetElement(1)
numberOfIterations = optimizer.GetCurrentIteration()
bestValue = optimizer.GetValue()print("Result = ")
print(" Translation X = " + str(translationAlongX))
print(" Translation Y = " + str(translationAlongY))
print(" Iterations    = " + str(numberOfIterations))
print(" Metric value  = " + str(bestValue))CompositeTransformType = itk.CompositeTransform[itk.D, Dimension]
outputCompositeTransform = CompositeTransformType.New()
outputCompositeTransform.AddTransform(movingInitialTransform)
outputCompositeTransform.AddTransform(registration.GetModifiableTransform())resampler = itk.ResampleImageFilter.New(Input=movingImage,Transform=outputCompositeTransform,UseReferenceImage=True,ReferenceImage=fixedImage,
)
resampler.SetDefaultPixelValue(100)OutputPixelType = itk.ctype("unsigned char")
OutputImageType = itk.Image[OutputPixelType, Dimension]
caster = itk.CastImageFilter[FixedImageType, OutputImageType].New(Input=resampler)
output_image_arr = itk.GetArrayFromImage(caster)  # 配准后的结果difference = itk.SubtractImageFilter.New(Input1=fixedImage, Input2=resampler)
intensityRescaler = itk.RescaleIntensityImageFilter[FixedImageType, OutputImageType
].New(Input=difference,OutputMinimum=itk.NumericTraits[OutputPixelType].min(),OutputMaximum=itk.NumericTraits[OutputPixelType].max(),
)
resampler.SetDefaultPixelValue(1)
intensityRescaler.Update()
difference_image_after_arr = itk.GetArrayFromImage(intensityRescaler.GetOutput())  # 配准后与原图像的差别resampler.SetTransform(identityTransform)
intensityRescaler.Update()
difference_image_before_arr = itk.GetArrayFromImage(intensityRescaler.GetOutput())  # 配准前与原图像的差别# output_image  difference_image_after  difference_image_before
plt.subplot(231), plt.imshow(itk.GetArrayFromImage(fixedImage), 'gray'), plt.title('fixedImage')
plt.subplot(232), plt.imshow(itk.GetArrayFromImage(movingImage), 'gray'), plt.title('movingImage')
plt.subplot(233), plt.imshow(output_image_arr, 'gray'), plt.title('output_image')
plt.subplot(234), plt.imshow(difference_image_after_arr, 'gray'), plt.title('difference_image_after')
plt.subplot(235), plt.imshow(difference_image_before_arr, 'gray'), plt.title('difference_image_before')
# plt.subplot(236), plt.imshow(itk.GetArrayFromImage(moving_smoothed_image), 'gray'), plt.title('moving_smoothed_image')
plt.show()

多模态互信息配准 Perform Multi Modality Registration With Viola Wells Mutual Information

原文地址: https://examples.itk.org/src/registration/common/performmultimodalityregistrationwithmutualinformation/documentation

效果图

在这里插入图片描述

源码:

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cmimport itkdim = 2
ImageType = itk.Image[itk.F, dim]
FixedImageType = ImageType
MovingImageType = ImageTypebaseDir = r'D:\learn\itk\itk5.3.0\ITK-5.3.0\Examples\Data'fixed_img_path = baseDir + r"\BrainT1SliceBorder20.png"
moving_img_path = baseDir + r"\BrainProtonDensitySliceShifted13x17y.png"fixed_img = itk.imread(fixed_img_path, itk.F)
moving_img = itk.imread(moving_img_path, itk.F)fixed_normalized_image = itk.normalize_image_filter(fixed_img)
fixed_smoothed_image = itk.discrete_gaussian_image_filter(fixed_normalized_image, variance=2.0)moving_normalized_image = itk.normalize_image_filter(moving_img)
moving_smoothed_image = itk.discrete_gaussian_image_filter(moving_normalized_image, variance=2.0)TransformType = itk.TranslationTransform[itk.D, dim]
OptimizerType = itk.GradientDescentOptimizer
MetricType = itk.MutualInformationImageToImageMetric[ImageType, ImageType]
RegistrationType = itk.ImageRegistrationMethod[ImageType, ImageType]
InterpolatorType = itk.LinearInterpolateImageFunction[ImageType, itk.D]
n_iterations = 200
transform = TransformType.New()
metric = MetricType.New()
optimizer = OptimizerType.New()
registrar = RegistrationType.New()
interpolator = InterpolatorType.New()registrar.SetFixedImage(fixed_smoothed_image)
registrar.SetMovingImage(moving_smoothed_image)
registrar.SetOptimizer(optimizer)
registrar.SetTransform(transform)
registrar.SetInterpolator(interpolator)
registrar.SetMetric(metric)
registrar.SetFixedImageRegion(fixed_img.GetBufferedRegion())
registrar.SetInitialTransformParameters(transform.GetParameters())
numberOfSamples = int(fixed_img.GetBufferedRegion().GetNumberOfPixels() * 0.01)
print('numberOfSamples:', numberOfSamples)
metric.SetNumberOfSpatialSamples(numberOfSamples)
metric.SetFixedImageStandardDeviation(0.4)
metric.SetMovingImageStandardDeviation(0.4)
metric.ReinitializeSeed(121212)optimizer.SetLearningRate(15.0)
optimizer.SetNumberOfIterations(n_iterations)
optimizer.MaximizeOn()def log_iteration():print('Iteration:', optimizer.GetCurrentIteration())print('Value:', optimizer.GetValue())print('CurrentPosition:', list(optimizer.GetCurrentPosition()))optimizer.AddObserver(itk.IterationEvent(), log_iteration)
registrar.Update()
print('-'*50)
print(f"Its: {optimizer.GetCurrentIteration()}")
print(f"Final Value: {optimizer.GetValue()}")
print(f"Final Position: {list(registrar.GetLastTransformParameters())}")ResampleFilterType = itk.ResampleImageFilter[MovingImageType, FixedImageType]
resample = ResampleFilterType.New(Transform=transform,Input=moving_img,Size=fixed_img.GetLargestPossibleRegion().GetSize(),OutputOrigin=fixed_img.GetOrigin(),OutputSpacing=fixed_img.GetSpacing(),OutputDirection=fixed_img.GetDirection(),DefaultPixelValue=100,
)
resample.Update()
output_image_arr = itk.GetArrayFromImage(resample.GetOutput())CheckerBoardFilterType = itk.CheckerBoardImageFilter[FixedImageType]
checker = CheckerBoardFilterType.New()
checker.SetInput1(fixed_img)
checker.SetInput2(resample.GetOutput())
checker.Update()
difference_image_after_arr = itk.GetArrayFromImage(checker.GetOutput())identityTransform = TransformType.New()
identityTransform.SetIdentity()
resample.SetTransform(identityTransform)
checker.Update()
difference_image_before_arr = itk.GetArrayFromImage(checker.GetOutput())# output_image  difference_image_after  difference_image_before
plt.subplot(231), plt.imshow(itk.GetArrayFromImage(fixed_img), 'gray'), plt.title('fixed_img')
plt.subplot(232), plt.imshow(itk.GetArrayFromImage(moving_img), 'gray'), plt.title('moving_img')
plt.subplot(233), plt.imshow(output_image_arr, 'gray'), plt.title('output_image')
plt.subplot(234), plt.imshow(difference_image_after_arr, 'gray'), plt.title('difference_image_after')
plt.subplot(235), plt.imshow(difference_image_before_arr, 'gray'), plt.title('difference_image_before')
# plt.subplot(236), plt.imshow(itk.GetArrayFromImage(moving_smoothed_image), 'gray'), plt.title('moving_smoothed_image')
plt.show()

Register Image to Another Using Landmarks 通过标记点配准图像

原文地址:https://examples.itk.org/src/registration/common/registerimagetoanotherusinglandmarks/documentation

效果图

在这里插入图片描述

源码

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cmimport itk# Perform 2D Translation Registration With Mean Squares
baseDir = r'D:\learn\itk\itk5.3.0\ITK-5.3.0\Examples\Data'
fixed_input_image = baseDir + r"\BrainProtonDensitySlice.png"
moving_input_image = baseDir + r"\BrainProtonDensitySliceShifted13x17y.png"PixelType = itk.ctype("float")
fixedImage = itk.imread(fixed_input_image, PixelType)
movingImage = itk.imread(moving_input_image, PixelType)Dimension = fixedImage.GetImageDimension()
ImageType = itk.Image[PixelType, Dimension]LandmarkPointType = itk.Point[itk.D, Dimension]
LandmarkContainerType = itk.vector[LandmarkPointType]fixed_landmarks = LandmarkContainerType()
moving_landmarks = LandmarkContainerType()
fixed_point = LandmarkPointType()
moving_point = LandmarkPointType()
fixed_point[0] = 66
fixed_point[1] = 79
moving_point[0] = 99
moving_point[1] = 116
fixed_landmarks.push_back(fixed_point)
moving_landmarks.push_back(moving_point)
fixed_point[0] = 115
fixed_point[1] = 81
moving_point[0] = 148
moving_point[1] = 117
fixed_landmarks.push_back(fixed_point)
moving_landmarks.push_back(moving_point)
fixed_point[0] = 75
fixed_point[1] = 139
moving_point[0] = 108
moving_point[1] = 176
fixed_landmarks.push_back(fixed_point)
moving_landmarks.push_back(moving_point)TransformInitializerType = itk.LandmarkBasedTransformInitializer[itk.Transform[itk.D, Dimension, Dimension]
]
transform_initializer = TransformInitializerType.New()
transform_initializer.SetFixedLandmarks(fixed_landmarks)
transform_initializer.SetMovingLandmarks(moving_landmarks)transform = itk.Rigid2DTransform[itk.D].New()
transform_initializer.SetTransform(transform)
transform_initializer.InitializeTransform()output = itk.resample_image_filter(movingImage,transform=transform,use_reference_image=True,reference_image=fixedImage,default_pixel_value=50,
)
print('transform:', transform)output_image_arr = itk.GetArrayFromImage(output)  # 配准后的结果OutputPixelType = itk.ctype("unsigned char")
OutputImageType = itk.Image[OutputPixelType, Dimension]difference = itk.SubtractImageFilter.New(Input1=fixedImage, Input2=output)
intensityRescaler = itk.RescaleIntensityImageFilter[ImageType, OutputImageType
].New(Input=difference,OutputMinimum=itk.NumericTraits[OutputPixelType].min(),OutputMaximum=itk.NumericTraits[OutputPixelType].max(),
)
intensityRescaler.Update()
difference_image_after_arr = itk.GetArrayFromImage(intensityRescaler.GetOutput())  # 配准后与原图像的差别# output_image  difference_image_after  difference_image_before
plt.subplot(221), plt.imshow(itk.GetArrayFromImage(fixedImage), 'gray'), plt.title('fixedImage')
plt.subplot(222), plt.imshow(itk.GetArrayFromImage(movingImage), 'gray'), plt.title('movingImage')
plt.subplot(223), plt.imshow(output_image_arr, 'gray'), plt.title('output_image')
plt.subplot(224), plt.imshow(difference_image_after_arr, 'gray'), plt.title('difference_image_after')
plt.show()

http://www.ppmy.cn/news/1278672.html

相关文章

npm run dev 与npm run serve的区别

npm run serve 和 npm run dev 是在开发阶段使用 npm 运行脚本的两种常见命令,它们的区别主要在于脚本的配置和执行方式。 npm run serve:通常与 Vue.js 相关的项目中使用。这个命令是在 package.json 文件中定义的一个脚本命令,用来启动开发…

软考高级难度排行榜,哪个科目相对较容易呢?

面对软考的5大高级科目,你是不是也想知道哪个科目相对较“容易”一些呢?今天,让我们一起来看看吧 软考高级科目岗位描述 首先,大家可以看一下官方发布的《计算机技术与软件专业技术资格(水平)考试岗位设置与岗位描述》中有关软考…

arduino+pir传感器练习和lcd屏幕库练习

// C code // #include <Adafruit_LiquidCrystal.h>//lcd屏幕库 库根据屏幕下载Adafruit_LiquidCrystal lcd_1(0);//定义lcd屏幕对象void setup() {pinMode(5, INPUT);//定义pir针脚lcd_1.begin(16, 2);/* begin(16, 2)&#xff1a;是 lcd_1 对象的一个方法调用&#xff…

Linux: config: CONFIG_NODES_SHIFT;numa;强制挂钩

文章目录 简介config NODES_SHIFT循环接口简介 node和numa算是强挂钩关系了。和node相关的,几乎全部是numa。所以不要疑惑node和numa的强关联性。 config NODES_SHIFT Redhat提供的是10,也就是支持1024个node,但实际上用不了这么多,但是为了通用性,设置了这么大,其实可…

ChatGPT真的不火了吗?

不是不火&#xff0c;而是不常用&#xff0c;所以才会产生这种错觉。。。 升级一个GPT4.0就可以体验GPT带来的震撼 实际上GPT在以肉眼可见的速度在增长 11月时ChatGPT服务崩的那几次&#xff0c;看一看大家用不上有多么着急就明白了~ 另外现在很方便普及了&#xff0c;国产…

mybatis-plus阻止全表更新与删除

BlockAttackInnerInterceptor 是mybatis-plus的一个内置拦截器&#xff0c;用于防止恶意的全表更新或删除操作。当你添加了这个拦截器后&#xff0c;它会检查即将执行的 sql语句&#xff0c;如果有尝试进行全表更新或删除的语句&#xff0c;该拦截器会阻止这些操作。 <!-- m…

Android Studio各种Gradle常见报错问题及解决方案

大家好&#xff0c;我是咕噜铁蛋&#xff01;在开发Android应用程序时&#xff0c;我们可能会遇到各种Gradle错误。这些错误可能来自不同的原因&#xff0c;例如依赖项问题、配置错误、版本冲突等。今天我通过搜索整理了一下&#xff0c;在这篇文章中&#xff0c;我将分享一些常…

Flink系列之:深入理解ttl和checkpoint,Flink SQL应用ttl案例

Flink系列之&#xff1a;深入理解ttl和checkpoint&#xff0c;Flink SQL应用ttl案例 一、深入理解Flink TTL二、Flink SQL设置TTL三、Flink设置TTL四、深入理解checkpoint五、Flink设置Checkpoint六、Flink SQL关联多张表七、Flink SQL使用TTL关联多表 一、深入理解Flink TTL …