How to correctly to combine a set of images into one dicom file?

238 views Asked by At

I am attempting to create a multi-frame DICOM file from a set of more than 300 sequential .PNG images. While I've successfully generated a DICOM file with 375 frames, the frames have overlapping and cropped images, not corresponding to the original intended images.

(Examples of actual and expected output at the end).

I'm working with Optical Coherence Tomography (OCT), and the frames are supposed to be consecutive images, each frame corresponding to one image.

Here is my code:

import os
import datetime
import numpy as np
import pydicom.encaps
from PIL import Image
from pydicom.dataset import FileMetaDataset, Dataset
from pydicom.uid import ExplicitVRLittleEndian


dt = datetime.datetime.now()

# Image folder and its contents
image_folder = r"E:\OCT\series_00\US000000"
image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')]
image_files.sort()

# DICOM file metadata
file_meta = FileMetaDataset()
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.14.1'  
file_meta.ImplementationClassUID = '1.2.3.4'

# Create a new multi-frame DICOM dataset
multi_frame_dataset = Dataset()
multi_frame_dataset.SOPClassUID = '1.2.840.10008.5.1.4.1.1.14.1'
multi_frame_dataset.PatientName = "Test^Name"
multi_frame_dataset.PatientID = "00-000-000"
multi_frame_dataset.ContentDate = dt.strftime('%Y%m%d')
multi_frame_dataset.ContentTime = dt.strftime('%H%M%S.%f')
multi_frame_dataset.is_little_endian = True
multi_frame_dataset.is_implicit_VR = False
multi_frame_dataset.SpecificCharacterSet = 'ISO_IR 100'

# List with 'pixel arrays' of all images (frames)
pixel_data = []

# Load and append each image to the pixel data list:
for image_file in image_files:
    image_path = os.path.join(image_folder, image_file)
    image = Image.open(image_path)
    pixel_array = np.array(image)
    pixel_data.append(pixel_array)

multi_frame_pixel_data = pydicom.encaps.encapsulate([frame.tobytes() for frame in pixel_data])

# Combine pixel data from all frames into the multi-frame DICOM
multi_frame_dataset.PixelData = multi_frame_pixel_data
multi_frame_dataset.Rows = pixel_data[0].shape[0]
multi_frame_dataset.Columns = pixel_data[0].shape[1]
multi_frame_dataset.NumberOfFrames = len(pixel_data)

# Set attributes for the multi-frame DICOM
multi_frame_dataset.SamplesPerPixel = 3
multi_frame_dataset.BitsAllocated = 8
multi_frame_dataset.BitsStored = 8
multi_frame_dataset.HighBit = 7
multi_frame_dataset.PixelRepresentation = 0

# Save the multi-frame DICOM file
save_path = r'C:\Desktop\New Folder\multi_frame.dcm'
multi_frame_dataset.save_as(save_path)

My output: Output

My expected output (that's a single image in .png format, supposed to be a frame):

Expected output

0

There are 0 answers