码迷,mamicode.com
首页 > 其他好文 > 详细

raw文件转mha文件

时间:2019-11-13 00:35:38      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:script   file path   ref   一个   http   numpy   efi   writer   simple   

raw格式

在体数据(volume)中,经常会遇到raw文件,raw文件就是其实就是所有体素组成的文件,raw文件必须还有一些描信息才能用(因为得知道数据的size,type,spacing等),就像.mhd文件是对raw文件的一个描述。在医学数据处理中,经常使用mha文件格式来对数据进行处理,因为mha文件格式比较简单,而且包含了所有的基本图像信息(之前一篇有简单介绍)。所以本文要介绍将raw格式的文件转为mha格式。其实也不一定是raw文件,因为不论是什么后缀名,数据的内容都不会变化。

代码

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

博主建立了一个git库,会把平时用的,觉得可以复用的医学数据处理的代码放进去,现在还很空,慢慢积累吧。https://github.com/MangoWAY/medicalImageScriptDemo

raw文件转mha文件

标签:script   file path   ref   一个   http   numpy   efi   writer   simple   

原文地址:https://www.cnblogs.com/WAoyu/p/11846248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!