背景
项目需求:对脑影像T1结构像进行配准和偏差矫正。 采用方法:调用远程linux的ants包+使用nipype进行配准和N4矫正(本项目中有pyqt5的需求,至于怎么在pycharm下配置自行百度。) Note:nipype提供了安装的docker,同组的师兄说可以直接下载docker就不用非得在linux上运行ants这些,但是本人对docker不熟悉(师兄也没用)就不打算这么做了。先安排个坑:docker的配置与使用,之后项目需要打包成docker环境再来补一下。 首先pycharm连接远端环境+本地写代码+远程跑,具体方法:https://www.cnblogs.com/Red-Heart-Match/p/16013112.html
配准
找到ants的安装目录,到bin文件夹下,如下图所示:
bin文件夹底下放置了我们需要运行的命令。可以看出来,有.sh结尾的也有直接一条命令的,以.sh结尾的是sh文件,需要使用source才能运行;直接一条命令的不需要source,只需要告诉os它们的路径即可运行。 一下为代码示例:
import os
from nipype.interfaces.ants import RegistrationSynQuick
import torch
import subprocess
from PyQt5.QtWidgets import QMessageBox, QProgressBar
from PyQt5 import QtWidgets
import sys
import logging
from PyQt5.QtCore import QThread
def registration(fix_image, move_image, output_path):
reg = RegistrationSynQuick()
output_path = output_path
fix_image = fix_image
move_image = move_image
reg.inputs.fixed_image = fix_image
reg.inputs.moving_image = move_image
reg.inputs.output_prefix = output_path
reg.inputs.num_threads = 2
cmdline = reg.cmdline
print(cmdline)
try:
cmd = 'export ANTSPATH=/home/limpid/ANTs/install/bin && source $ANTSPATH/{0}'.format(cmdline)
task = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
res = task.stdout.decode('utf-8')
with open('out.txt', 'w+') as file:
file.write(res)
QMessageBox.information(QtWidgets.QWidget(), 'messagebox', 'finished! See output file', QMessageBox.Yes)
return 1
except BaseException as err:
print('err\n', err)
QMessageBox.information(QtWidgets.QWidget(), 'messagebox', 'error, see log file', QMessageBox.Yes)
return -1
N4biasfiledcorrection
import os
import subprocess
from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtWidgets
import SimpleITK as sitk
from nipype.interfaces.ants import N4BiasFieldCorrection
def n4correction(in_file, out_path, out_file, image_type=sitk.sitkFloat64):
'''
:param in_file:
:param out_file:
:param image_type:
:return:
'''
correct = N4BiasFieldCorrection()
correct.inputs.input_image = in_file
correct.inputs.output_image = os.path.join(out_path, out_file)
try:
cmdline = correct.cmdline
cmd = 'export ANTSPATH=/home/limpid/ANTs/install/bin && $ANTSPATH/{0}'.format(cmdline)
print(cmd)
task = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
res = task.stdout.decode('utf-8')
with open('out.txt', 'w+') as file:
file.write(res)
QMessageBox.information(QtWidgets.QWidget(), 'messagebox', 'finished! See output file', QMessageBox.Yes)
return 1
except BaseException as err:
print('err', err)
QMessageBox.warning(QtWidgets.QWidget(), 'messagebox', 'error, see log file', QMessageBox.Yes)
return -1
|