Converting dicom file raising an OSError: cannot write mode I;16 as JPEG

I am trying to convert a Computed Radiography dicom file to jpeg using the code below but its raising an OSError: cannot write mode I;16 as JPEG. Here is the code I am using to convert:

    ds = read_file('Dicom_files/' + dicomname)
    im = fromarray(ds.pixel_array)
    im.save('./Jpeg/' + dicomname + '.jpg')

It's raising the following error:

Traceback (most recent call last):
  File "/home/wisdom/Desktop/DCM_OUPUT_WRITING/info2.py", line 118, in <module>
    img = take_dicom(i)
  File "/home/wisdom/Desktop/DCM_OUPUT_WRITING/info2.py", line 28, in take_dicom
    final_img = im.save('./Jpeg/' + dicomname + '.jpg')
  File "/usr/local/lib/python3.9/dist-packages/PIL/Image.py", line 2240, in save
    save_handler(self, fp, filename)
  File "/usr/local/lib/python3.9/dist-packages/PIL/JpegImagePlugin.py", line 631, in _save
    raise OSError(f"cannot write mode {im.mode} as JPEG") from e
OSError: cannot write mode I;16 as JPEG

How can I solve this?


Solution 1:

Regular JPEG uses 8 bits per sample. If your data is 16-bit, you'll need to either:

  • scale it down (thereby losing radiometric resolution) and use JPEG, or
  • use a format that supports 16-bit such as PNG or TIFF.