raw file file transfer mha

raw format

In volume data (volume), we often encounter raw files, raw files is actually a file consisting of all voxels, raw files must be some trace information can be used (because the data have to know the size, type, spacing, etc.) like .mhd file is a description of the raw file. In the medical data processing, file format often used mha to process the data, because mha file format is relatively simple, but also contains all the basic image information ( before there is a brief introduction ). So this article to introduce the raw file format into mha format. In fact, not necessarily the raw file, because no matter what name suffix, the content data will not change.

Code

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

Bloggers created a git repository, will usually use, processing of medical data that can reuse code into them, and now is still empty, and slowly accumulate it. https://github.com/MangoWAY/medicalImageScriptDemo

Guess you like

Origin www.cnblogs.com/WAoyu/p/11846248.html