I am writing a code that creates DICOM file from array in Python. So the function takes 3D array and creates DICOM for each slice in z-dimension.
When I read the created DICOM files with pydicom, it gives me error:
The length of the pixel data in the dataset (524288 bytes) doesn’t match the expected length (5242880 bytes). The dataset may be corrupted or there may be an issue with the pixel data handler.
Can someone help me with my code, please? What am I doing wrong?
def dicom_gen(NPS3Darray, pixel_spacing, slice_thickness, folder_name):
parent_dir = "/Users/Desktop/test NPS3D/"
path = os.path.join(parent_dir, folder_name)
os.mkdir(path)
i = 1
slices = np.shape(NPS3Darray)[0]
rows = np.shape(NPS3Darray)[1]
cols = np.shape(NPS3Darray)[2]
while i <= slices:
image2d = []
image2d = NPS3Darray[(i-1),:, :].astype(np.uint16)
meta = pydicom.Dataset()
meta.MediaStorageSOPClassUID = pydicom._storage_sopclass_uids.CTImageStorage
meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid()
meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian
ds = Dataset()
ds.file_meta = meta
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.SOPClassUID = pydicom._storage_sopclass_uids.CTImageStorage
ds.PatientName = "Test^Firstname"
ds.PatientID = "123456"
ds.Modality = "CT"
ds.SeriesInstanceUID = pydicom.uid.generate_uid()
ds.StudyInstanceUID = pydicom.uid.generate_uid()
ds.FrameOfReferenceUID = pydicom.uid.generate_uid()
ds.BitsStored = 16
ds.BitsAllocated = 16
ds.SamplesPerPixel = 1
ds.HighBit = 15
#ds.ImagesInAcquisition = "1"
ds.Rows = image2d.shape[0]
ds.Columns = image2d.shape[1]
ds.InstanceNumber = i
ds.SliceLocation = i*slice_thickness
ds.SliceThickness = slice_thickness
ds.PatientOrientation = r"LP"
ds.ImageType = r"ORIGINALPRIMARYAXIAL"
ds.ImagePositionPatient = r"-120.8572-120.8572%.2f" % (787.50+i*slice_thickness)
ds.ImageOrientationPatient = r"1.00000.00000.00000.000001.00000.00000"
ds.RescaleIntercept = "0"
ds.RescaleSlope = "1"
ds.PixelSpacing = r"%.3f%.3f" % (pixel_spacing, pixel_spacing)
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 1
ds.NumberOfFrames = slices
ds.Rows = rows
ds.Columns = cols
pydicom.dataset.validate_file_meta(ds.file_meta, enforce_standard=True)
ds.PixelData = image2d.tobytes()
ds.save_as(r"%s/slice%s.dcm" % (path, i), write_like_original=False)
i += 1
user24819415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.