radoss-org / radstract

Radstract provides a range of helper functions for working with Medical Data and analysis methods with that data.
Apache License 2.0
0 stars 1 forks source link

Support exporting JEPG Compressed DICOMs #9

Open Sharpz7 opened 4 months ago

Sharpz7 commented 4 months ago
def convert_images_to_dicom(
    images: Image.Image,
) -> pydicom.Dataset:

    empty_dicom = create_empty_dicom(dicom_type=DicomTypes.SERIES_ANONYMIZED)

    img_byte_list = []
    # re-write the above to use the images directly
    for img in images:
        with BytesIO() as output:
            img.save(output, format="jpeg")
            img_byte_list.append(output.getvalue())

    empty_dicom.PixelData = encapsulate([x for x in img_byte_list])
    empty_dicom["PixelData"].is_undefined_length = True
    empty_dicom.is_implicit_VR = False
    empty_dicom.LossyImageCompression = "01"
    empty_dicom.LossyImageCompressionRatio = 10  # default jpeg
    empty_dicom.LossyImageCompressionMethod = "ISO_10918_1"
    empty_dicom.file_meta.TransferSyntaxUID = "1.2.840.10008.1.2.4.51"

    empty_dicom.NumberOfFrames = len(images)
    empty_dicom.Rows, empty_dicom.Columns = (
        images[0].size[1],
        images[0].size[0],
    )

    empty_dicom.file_meta.TransferSyntaxUID = "1.2.840.10008.1.2.4.51"
    empty_dicom.PlanarConfiguration = 0

    # forces write_like_original=False
    with BytesIO() as output:
        empty_dicom.save_as(output, write_like_original=False)
        output.seek(0)
        empty_dicom = pydicom.dcmread(output)

    return empty_dicom

Make sure that we can open them fine from radstract.

Sharpz7 commented 3 months ago

It is now clear we need to be more careful than the above, giving more options for the types of compression we support, and how faithful we are to non-RGB types (like monochrome2)

Support lossless, support lowest lossy dicom-native, Support lowest lossy custom encoder/decoder Support customisable compression lossy dicom-native