{"cells":[{"metadata":{},"cell_type":"markdown","source":"Converting dicom data to png/jpg may look straightforward and there is going to be many notebooks doing it simple way - just rescaling it.\n\nHowever, you must consider, that raw dicom data is not actually linearly convertable to \"human-friendly\" png/jpg. \nIn fact, most of DICOM's store pixel values in exponential scale, which is resolved by standard standard DICOM viewers.\n\nSo in order to get jpg/png as radiologists would initially see in their workspace, you need to apply some transformations. \nDICOM metadata stores information how to make such \"human-friendly\" transformations.\n\nAn example code I use daily can be found below:"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"img = read_xray('../input/vinbigdata-chest-xray-abnormalities-detection/train/0108949daa13dc94634a7d650a05c0bb.dicom')\nplt.figure(figsize = (12,12))\nplt.imshow(img, 'gray')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"What if hadn't fixed MONOCHROME issue:"},{"metadata":{"trusted":true},"cell_type":"code","source":"img = read_xray('../input/vinbigdata-chest-xray-abnormalities-detection/train/0108949daa13dc94634a7d650a05c0bb.dicom', fix_monochrome = False)\nplt.figure(figsize = (12,12))\nplt.imshow(img, 'gray')","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}