Skip to content

Instantly share code, notes, and snippets.

@rahulremanan
Last active August 23, 2021 03:55
Show Gist options
  • Save rahulremanan/56797ef8471e1e859e3571035addceb2 to your computer and use it in GitHub Desktop.
Save rahulremanan/56797ef8471e1e859e3571035addceb2 to your computer and use it in GitHub Desktop.
Handling DICOM X-Ray images
import pydicom, numpy as np
from pydicom.pixel_data_handlers.util import apply_voi_lut
def readDICOM(path, optimize_display=True, monochrome_correction=True):
dcm = pydicom.read_file(path)
dcm_arr = dcm.pixel_array
if optimize_display:
dcm_arr = apply_voi_lut(dcm_array, dcm)
if monochrome_correction and dcm.PhotometricInterpretation == 'MONOCHROME1':
dcm_arr = np.amax(dcm_arr) - dcm_arr
return {'DICOM array': dcm_arr, 'DICOM object': dcm}
def uint8_convert(arr):
arr = arr - np.min(arr)
if np.max(arr) != 0:
arr = arr / np.max(arr)
return (arr * 255).astype(np.uint8)
if __name__ == "__main__":
path = '/path/to/dicom/image.dcm'
optimize_display = True
monochrome_correction = True
dcm_arr = readDICOM(path,
optimize_display=optimize_display,
monochrome_correction=monochrome_correction)['DICOM array']
dcm_uint8_arr = uint8_convert(dcm_arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment