Gerome Pistre
Gerome Pistre

Reputation: 467

python read and convert raw 3d image file

I am working with ct scans medical images in raw format. It is basically a 3d matrix of voxels (512*512*nb of slices). I'd like to extract each slice of the file into separate files.

import numpy as np
import matplotlib.pyplot as plt

# reading the raw image into a string. The image files can be found at:
# https://grand-challenge.org/site/anode09/details/
f = open('test01.raw', 'rb')
img_str = f.read()

# converting to a uint16 numpy array
img_arr = np.fromstring(img_str, np.uint16)

# get the first image and plot it
im1 = img_arr[0:512*512]
im1 = np.reshape(im1, (512, 512))
plt.imshow(im1, cmap=plt.cm.gray_r)
plt.show()

The result definitely looks like a chest ct scan, but the texture of the image is strange, as if the pixels were misplaced.

enter image description here

Some relevant info might be located in the associated .mhd info file, but I'm not sure where to look:

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 = RPI
ElementSpacing = 0.697266 0.697266 0.7
DimSize = 512 512 459
ElementType = MET_SHORT
ElementDataFile = test01.raw

Upvotes: 3

Views: 9782

Answers (1)

max9111
max9111

Reputation: 6482

Try it this way:

Dim_size=np.array((512,512,459),dtype=np.int) #Or read that from your mhd info File

f = open(FileName,'rb') #only opens the file for reading
img_arr=np.fromfile(f,dtype=np.uint16)
img_arr=img_arr.reshape(Dim_size[0],Dim_size[1],Dim_size[2])

if you are Memory limited read the file in chunks

f = open(FileName,'rb') #only opens the file for reading
for i in range(0,Dim_size[2]):
    img_arr=np.fromfile(f,dtype=np.uint16,count=Dim_size[0]*Dim_size[1])
    img=img.reshape(Dim_size[0],Dim_size[1])
    #Do something with the Slice

A good way to show what's actually in the raw- File would also be to read it in ImageJ. For reading such ITK compatible files, there is even a PlugIn available, but direct raw import should also work. https://imagej.net/Welcome http://ij-plugins.sourceforge.net/plugins/3d-io/

Upvotes: 4

Related Questions