2

I am trying to save a set of images in dicom format out of python. I will only be extracting the PixelData field, so I am trying to do it using the minimum amount of code/tags. I am reading files using pydicom:

ds = dicom.read_file(currentDir + file)
Image = ds.pixel_array 

Unfortunately, there doesn't appear to be a function dicom.write_file(filename,header=MakeOneUp). Could you suggest the simplest way to write numpy arrays out as dicom images, with no reliance on reading dicoms/copying headers. I am trying to do it using this example:

from dicom.dataset import Dataset, FileDataset

file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2'
file_meta.MediaStorageSOPInstanceUID = "1.2.3"
file_meta.ImplementationClassUID = "1.2.3.4"

ds = FileDataset(FullPath, {}, file_meta=file_meta, preamble=b"\0" * 128)

ds.PatientName = "Test^Name"
ds.PatientID = "00-000-000"

# Set the transfer syntax
ds.is_little_endian = True
ds.is_implicit_VR = True

# Set creation date/time
dt = datetime.datetime.now()
ds.ContentDate = dt.strftime('%Y%m%d')
timeStr = dt.strftime('%H%M%S.%f')  # long format with micro seconds
ds.ContentTime = timeStr

However, when I get to the image, it breaks down:

ds.PixelData = Image[:,:,l]
# Alternatively 
# ds.pixel_array = np.ascontiguousarray(Image[:,:,l]), but this isn't a standard field?
ds.save_as(FullPath)

This fails with an error: If I try to do

np.ascontiguousarray(Image[:,:,l])

this doesn't dicom.read_file back as a human readable array.

Thank you

P.S: Was asked for error traceback.

ds.PixelData = np.ascontiguousarray(Image[:,:,l]) 
ds.save_as(FullPath)

Results in:

Traceback (most recent call last):
  File "/home/m047659/Programs/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-078b166fa765>", line 1, in <module>
    ds.save_as(FullPath)
  File "/home/m047659/Programs/anaconda3/lib/python3.6/site-packages/dicom/dataset.py", line 491, in save_as
    dicom.write_file(filename, self, write_like_original)
  File "/home/m047659/Programs/anaconda3/lib/python3.6/site-packages/dicom/filewriter.py", line 356, in write_file
    write_dataset(fp, dataset)
  File "/home/m047659/Programs/anaconda3/lib/python3.6/site-packages/dicom/filewriter.py", line 200, in write_dataset
    write_data_element(fp, dataset[tag], dataset_encoding)
  File "/home/m047659/Programs/anaconda3/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/m047659/Programs/anaconda3/lib/python3.6/site-packages/dicom/tagtools.py", line 21, in tag_in_exception
    raise type(e)(err)
ValueError: Invalid tag (7fe0, 0010): ndarray is not C-contiguous
illan
  • 163
  • 1
  • 13
  • Could you add the full error traceback? – nosklo Jul 12 '18 at 19:47
  • 2
    maybe this will help: https://stackoverflow.com/questions/14350675/create-pydicom-file-from-numpy-array – dr_agon Jul 12 '18 at 21:17
  • Old question but the simplest way to "How to write an image as dicom in python?" atm is to use simpleitk. See *Dave Chen's answer https://stackoverflow.com/questions/58348032/from-numpy-array-to-dicom/59216736#59216736* – Max Kuchenkiller Sep 16 '22 at 14:09

1 Answers1

1

You need to assign PixelData a bytes string representation of the Image. Image is a numpy array and needs to be coverted to a bytes string.

ds.PixelData = Image.tobytes()

You also need to set other image related attributes such as Rows, Columns, PixelRepresentation, etc for pixel_array to be populated correctly. See http://dicom.nema.org/medical/dicom/2014c/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.3 .

user2522981
  • 163
  • 3
  • 18