在体数据(volume)中,常常会遇到raw文件,raw文件就是其实就是全部体素组成的文件,raw文件必须还有一些描信息才能用(由于得知道数据的size,type,spacing等),就像.mhd文件是对raw文件的一个描述。在医学数据处理中,常用mha文件格式来对数据进行处理,由于mha文件格式比较简单,并且包含了全部的基本图像信息(以前一篇有简单介绍)。因此本文要介绍将raw格式的文件转为mha格式。其实也不必定是raw文件,由于不管是什么后缀名,数据的内容都不会变化。html
import SimpleITK as itk import numpy as np import os def raw2mha(inpath,outpath,size,spacing,intype='uint16',outtype='uint16'): """ parameter: inpath:raw file path outpath:raw out file path size:raw file size(z,y,x) such as (94,256,256) spacing:raw file pixel spacing. intype:raw file data type,default is uint16 """ #利用np从文件读取文件 data = np.fromfile(inpath,dtype=intype) #reshape数据,这里要注意读入numpy的时候,对应是(z,y,x) data = data.reshape(size) #设置输出时的数据类型 data = data.astype(outtype) #转成itk的image img:itk.Image = itk.GetImageFromArray(data) #设置pixel spacing img.SetSpacing(spacing) #输出文件 s = itk.ImageFileWriter() s.SetFileName(outpath) s.Execute(img) def main(): filepath = "test.raw" datatype = 'uint16' size = (94,256,256) spacing = (0.97,0.97,2.5) outname = "test.mha" raw2mha(filepath,outname,size,spacing,datatype) if __name__ == "__main__": main()
博主创建了一个git库,会把平时用的,以为能够复用的医学数据处理的代码放进去,如今还很空,慢慢积累吧。https://github.com/MangoWAY/medicalImageScriptDemogit