How to write DICOM file from array in Python?

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):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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

New contributor

user24819415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật