raw文件轉mha文件

raw格式

在體數據(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

博主創建了一個git庫,會把平時用的,以爲能夠複用的醫學數據處理的代碼放進去,如今還很空,慢慢積累吧。https://github.com/MangoWAY/medicalImageScriptDemogit

相關文章
相關標籤/搜索