这样操作能保存头文件 保存的文件能够放入 itksnap
def img2strip(imgpath,strippath,savepath):
img = nib.load(imgpath)
imgdata = img.get_fdata()
stripdata = nib.load(strippath).get_fdata()
newimgdata = imgdata * stripdata
newimg = nib.Nifti1Image(newimgdata,img.affine)
nib.save(newimg,savepath)```
rawpath = r'C:\Users\tangx\Desktop\raw'
sixpath = r'C:\Users\tangx\Desktop\six'
dirs = os.listdir(rawpath)
for i,dir in enumerate(dirs):
dirpath = os.path.join(rawpath,dir)
filenames = os.listdir(dirpath)
imgpath = os.path.join(dirpath,filenames[0])
strippath = os.path.join(dirpath,filenames[2])
if i<10:
strname = f'00{i}{filenames[0]}'
elif i<100:
strname = f'0{i}{filenames[0]}'
else:
strname = f'{i}{filenames[0]}'
savepath = os.path.join(sixpath,strname)
img2strip(imgpath,strippath,savepath)
发现一个问题 用get_fdata会导致数据类型从int16变成float 导致图像intensity变化 用get data虽然会警告 但是 存储的intensity不会变化 同时还有一个错误就是我的strip用错了 用成了segmentation
更新的代码
def img2strip(imgpath,strippath,savepath):
img = nib.load(imgpath)
imgdata = img.get_data()
print(imgdata.dtype)
strip = nib.load(strippath)
stripdata = strip.get_data()
print(stripdata.dtype)
newimgdata = imgdata * stripdata
print(newimgdata.dtype)
newimg = nib.Nifti1Image(newimgdata,img.affine)
nib.save(newimg,savepath)
|