4

Here is what I am trying to accomplish in Python (please keep in mind that I'm relatively new to Python):

  1. Convert a DICOM image into a list of xyz coordinates along with their respective pixel values and export the list to a .csv file.
  2. Regenerate the same image from the list of xyz coordinates and pixel values generated in the previous task.

So far, I have been able to read in the dicom images and convert them into an array through the use of pydicom and numpy. I've also been able to extract pixel and coordinate values through several for loops and export that list as a .csv. But there has to be a better way of doing this to maintain some sort of quality control, because when I try to regenerate the images (through the use of another set of for loops), I don't get the original image.

I need both functions to run separately in different python scripts.

This is what I have so far:

    #Raster through all pixels and copy each value and coordinates to arrays
    rc_cntr = 0
    for r in range(0,img_rows):
                for c in range(0,img_cols):
                    pixel = dcmarray[r, c]
                    rArray[rc_cntr] = r
                    cArray[rc_cntr] = c
                    zArray[rc_cntr] = z_cntr
                    imgArray[rc_cntr] = dcmarray[r,c]
                    rc_cntr = rc_cntr + 1;

    #Combine arrays into one file
            XYZV = numpy.column_stack([rArray,cArray,zArray, imgArray])
            numpy.savetxt(output_path,XYZV,'%0i','\t') #Save XYZV files for each image

Any help on this matter would be greatly appreciated.

Cheers AFH

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Masrawy
  • 41
  • 1
  • 3

1 Answers1

1

I am not very familiar with DICOM, but looking at the pydicom docs I think the following should work:

import dicom
import numpy as np

ds = dicom.read_file('your_file.dcm')
planes, rows, cols = ds.NumberofFrames, ds.Columns, ds.Rows
image = ds.pixel_array # should have shape (planes, rows, cols)

# to get data and coords to write to CSV
image_data = image.ravel()
z, y, x = np.meshgrid(np.arange(planes), np.arange(rows), np.arange(cols),
                      indexing='ij').T

# to write CSV read image back into DICOM file
planes, rows, cols = np.ptp(z)+1, np.ptp(y)+1, np.ptp(x)+1
image = np.zeros((planes, rows, cols), dtype=image_data.dtype)
image[z, y, x] = image_data

ds.NumberofFrames, ds.Columns, ds.Rows = planes, rows, cols
ds.PixelData = image.tostring()
ds.save_as('another_file.dcm')
Jaime
  • 65,696
  • 17
  • 124
  • 159
  • I've been able to run the code, just having a hard time saving to .csv and reading it back in to complete the cycle. – Masrawy Jul 29 '13 at 15:45