Search code examples
python-2.7vtkimageset

Create .mhd File from 2D Images


I am studying 3d reconstructions in medikal and I have image dataset which including lots of 2d images My code needs a .raw file How can I convert my images to .raw file (My images are png file and the output should be .mhd file) I used this .mhd file for my code :

   ObjectType = Image
NDims = 3
BinaryData = True
BinaryDataByteOrderMSB = False
CompressedData = False
TransformMatrix = -1 0 0 0 1 0 0 0 -1
Offset = 0 0 0
CenterOfRotation = 0 0 0
AnatomicalOrientation = LAS
ElementSpacing = 0.9375 0.9375 1.5
ITK_InputFilterName = MetaImageIO
DimSize = 256 256 94
ElementType = MET_SHORT
ElementDataFile = FullHead.raw

But I need a .raw file for using .mhd file On the other hand I cannot convert to.rawfile from png images


Solution

  • You have to specify, what kind of input data do you have. Are they e.g. DICOM images? TIFF? Any other format? It would be the easiest, if you provided one exemplary image.

    Another think, what kind of output do you need? MHD (MetaImage Header) normaly contains just metadata, RAW is exact image.

    Improved answer below

    Raw data is just a content of png image you have read. So siply read images, change 2D matrix into 1D array and concatenate all the files:

    from PIL import Image
    import numpy as np
    slices = []
    for afile in imageList:
        img = Image.open(afile).convert('L')
        arr = np.array(img).flatten('C')  #if image gets transposed, then 
    flatten('F')
        slices.append(arr)
    
    arr2 = np.array(slices).flatten('C').astype('short')
    arr2.tofile("OutputFile.raw")