Convert Images into Dicom with python

49 Views Asked by At

I have problems trying to convert BMP-Images into DICOM. My Python Script list all the BMP Files in the Directory and convert them into a Dicom Dataset. I can run the code but I get a strange result. I don't know what the problem could be, this is my first time working with image processing. Please help me i am lerning:(

def convert_bmps_to_dicoms(bmp_dir, dicom_output_dir):
# Create output directory if it doesn't exist
if not os.path.exists(dicom_output_dir):
    os.makedirs(dicom_output_dir)

# List all BMP files in the directory
bmp_files = [f for f in os.listdir(bmp_dir) if f.endswith('.bmp')]

if not bmp_files:
    print("No BMP files found in the directory.")
    return

for bmp_file in bmp_files:
    # Load BMP image
    bmp_path = os.path.join(bmp_dir, bmp_file)
    image = Image.open(bmp_path)
    image_array = np.array(image)

    # Create DICOM dataset
    ds = FileDataset(os.path.join(dicom_output_dir, f"{os.path.splitext(bmp_file)[0]}.dcm"), {},
                     file_meta=Dataset())
    ds.Modality = 'OT'
    ds.PatientName = "Test^Firstname"
    ds.PatientID = "123456"
    ds.PatientBirthDate = "20000101"
    ds.PatientSex = "F"
    ds.StudyInstanceUID = pydicom.uid.generate_uid()  # Random Study Instance UID
    ds.SeriesInstanceUID = "1.2.826.0.1.3680043.9.3813.1.1.222222"
    ds.SOPInstanceUID = pydicom.uid.generate_uid()
    ds.SamplesPerPixel = 1
    ds.PhotometricInterpretation = "MONOCHROME2"
    ds.Rows = 512  # Set rows to 512
    ds.Columns = 512  # Set columns to 512
    ds.BitsAllocated = 8
    ds.BitsStored = 8
    ds.HighBit = 7
    ds.PixelRepresentation = 0
    ds.PixelData = image_array.tobytes()

    # Add custom attribute for BMP file name
    ds.BMPFileName = bmp_file

    # Write DICOM dataset to file
    ds.save_as(os.path.join(dicom_output_dir, f"{os.path.splitext(bmp_file)[0]}.dcm"))
    print(f"DICOM file {bmp_file}.dcm saved successfully in {dicom_output_dir}.")
0

There are 0 best solutions below