Tag Archives: DICOM

Python writes DICOM file (attributeerror: ‘filemetadataset’ object has no attribute ‘transfersyntax uid’ solution)

Write to DICOM file

import numpy as np
import matplotlib.pyplot as plt
import pydicom
import sys

def InitDicomFile():
    infometa = pydicom.dataset.Dataset()
    infometa.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
    infometa.ImplementationVersionName = 'Python ' + sys.version
    infometa.MediaStorageSOPClassUID = 'CT Image Storage'
    infometa.FileMetaInformationVersion = b'\x00\x01'
    return infometa
    
filename = r'E:\34.dcm'
# ds = pydicom.dcmread(filename) # Read Tags from dicom image
ds = pydicom.read_file(filename) # Read Tags of the dicom image
info = pydicom.dataset.FileDataset({},ds) 
temp = pydicom.dcmread(filename).pixel_array # read in DICOM image and convert to numpy
img = temp.astype('uint16')
info.PixelData = img.tobytes()
infometa = InitDicomFile() # must be initialized otherwise read in will prompt an error
info = pydicom.dataset.FileDataset({},info,is_implicit_VR =True, file_meta=infometa)
# info = pydicom.dataset.FileDataset({},info) # Read without file_meta=infometa will prompt an error
info.save_as(r'M:\result.dcm')
# Verify that the newly stored DICOM can be read in
f = pydicom.dcmread(r'M:\result.dcm',force=True)
plt.imshow(f.pixel_array,'gray')
plt.show()

If there are not the following two lines, reading the stored DICOM file will prompt the following error:

infometa = InitDicomFile()
info = pydicom.dataset.FileDataset({},info,is_implicit_VR =True, file_meta=infometa)

AttributeError: ‘FileMetaDataset’ object has no attribute ‘TransferSyntaxUID’