{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Pydicom Crash Course: 10 Essential Examples You Need to Know\n## Here you can find what a beginner needs!\n\n## Introduction\n    Welcome to this detailed crash course on the pydicom library! Whether you're a healthcare professional, a data scientist, or a coding enthusiast, if you are interested in medical imaging and DICOM files, this guide is for you.\n\n## Prerequisites\n    Python 3.x installed\n    pydicom library installed (You can install it via pip: <pip install pydicom>)","metadata":{}},{"cell_type":"markdown","source":" ## 1. Reading a DICOM file","metadata":{}},{"cell_type":"code","source":"try:\n    import pydicom\n    \nexcept:\n    !pip install pydicom\n    \n# Specify the path to your DICOM file\ndicom_file_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/1002.dcm'\n\n# Read the DICOM file\nds = pydicom.dcmread(dicom_file_path)\n    \n    \nds","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.043171Z","iopub.execute_input":"2023-10-08T01:39:31.043974Z","iopub.status.idle":"2023-10-08T01:39:31.280067Z","shell.execute_reply.started":"2023-10-08T01:39:31.043937Z","shell.execute_reply":"2023-10-08T01:39:31.27889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* As you can see here, DICOM files store metadata information alongside with the raw pixels. Understanding this metadata is important when dealing with image analysis.\n\n* Metadata includes information like patient name, modality, and much more. The FileDataset object can be iterated to view all the metadata tags. \n\n* You can check this radiopaedia article [here](http://https://radiopaedia.org/articles/digital-imaging-and-communications-in-medicine-dicom) for more information. ","metadata":{}},{"cell_type":"markdown","source":"## 2. Displaying DICOM Metadata\n* You can also iterate through the dicom metadata to access its elements.","metadata":{}},{"cell_type":"code","source":"# Loop through the dataset and display metadata\nfor i in ds:\n    print(\"Here you go!\")\n    print(i)\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.282137Z","iopub.execute_input":"2023-10-08T01:39:31.282977Z","iopub.status.idle":"2023-10-08T01:39:31.290428Z","shell.execute_reply.started":"2023-10-08T01:39:31.282938Z","shell.execute_reply":"2023-10-08T01:39:31.289297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3.Displaying the Image\n The DICOM file also includes the actual medical image, stored as a pixel array. You can visualize this using matplotlib, a plotting library for Python.","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Visualize the DICOM image\nplt.imshow(ds.pixel_array, cmap='gray')\nplt.axis('off')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.291815Z","iopub.execute_input":"2023-10-08T01:39:31.292154Z","iopub.status.idle":"2023-10-08T01:39:31.511518Z","shell.execute_reply.started":"2023-10-08T01:39:31.292128Z","shell.execute_reply":"2023-10-08T01:39:31.510744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4.Modifying Metadata\n* There may be scenarios where you need to alter the metadata of a DICOM file. This could be as simple as correcting a patient's name, study date, institution info or as complex as updating study details. The FileDataset object allows you to modify these fields directly.","metadata":{}},{"cell_type":"code","source":"# Assign a patient name in the metadata even it's not present in the file\nds.PatientName = \"John Doe\"\n\nds.PatientName","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.51353Z","iopub.execute_input":"2023-10-08T01:39:31.513953Z","iopub.status.idle":"2023-10-08T01:39:31.519325Z","shell.execute_reply.started":"2023-10-08T01:39:31.513925Z","shell.execute_reply":"2023-10-08T01:39:31.518705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 5. Saving a New DICOM File\n* After making changes to the DICOM file, either to its metadata or pixel data, you may want to save it. The save_as method allows you to save the current FileDataset object as a new DICOM file.","metadata":{}},{"cell_type":"code","source":"# Save the modified DICOM file\nds.save_as('sample_file0.dcm')","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.520518Z","iopub.execute_input":"2023-10-08T01:39:31.520994Z","iopub.status.idle":"2023-10-08T01:39:31.532226Z","shell.execute_reply.started":"2023-10-08T01:39:31.520969Z","shell.execute_reply":"2023-10-08T01:39:31.53156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 6. Converting DICOM to Other Image Formats\n* Sometimes, you may need to convert a DICOM image into a more common image format like JPEG or PNG. You can use the PIL library to accomplish this.","metadata":{}},{"cell_type":"code","source":"from PIL import Image\n\n# Convert the DICOM image to PNG format\nimage = Image.fromarray(ds.pixel_array)\nimage.save('sample_image.png')\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:39:31.533445Z","iopub.execute_input":"2023-10-08T01:39:31.534017Z","iopub.status.idle":"2023-10-08T01:39:31.666306Z","shell.execute_reply.started":"2023-10-08T01:39:31.533991Z","shell.execute_reply":"2023-10-08T01:39:31.66526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 7. Anonymizing DICOM Files\n* Anonymizing DICOM files is essential for protecting patient privacy, especially when sharing files for research or educational purposes. Certain fields like patient name and ID can be nullified or replaced with pseudonyms.","metadata":{}},{"cell_type":"code","source":"# Anonymize the DICOM file\nds.PatientName = \"\"\nds.PatientID = \"\"\n\nds","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:43:16.861712Z","iopub.execute_input":"2023-10-08T01:43:16.862106Z","iopub.status.idle":"2023-10-08T01:43:16.86893Z","shell.execute_reply.started":"2023-10-08T01:43:16.86207Z","shell.execute_reply":"2023-10-08T01:43:16.867914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 8. Pixel Data Manipulation\n\n* In some cases, you may need to manipulate the pixel data directly. This could be for image enhancement, filtering, or other pre-processing steps. The pixel data can be accessed and modified within the FileDataset object.","metadata":{}},{"cell_type":"code","source":"# Invert the DICOM image\ninv_pixel_array = (ds.pixel_array)*-1\n\n# Visualize the DICOM image\nplt.imshow(inv_pixel_array, cmap='gray')\nplt.axis('off')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:51:09.028636Z","iopub.execute_input":"2023-10-08T01:51:09.029329Z","iopub.status.idle":"2023-10-08T01:51:09.235799Z","shell.execute_reply.started":"2023-10-08T01:51:09.029295Z","shell.execute_reply":"2023-10-08T01:51:09.234351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Sometimes, the pixel values in the DICOM file need to be transformed using the Rescale Slope and Rescale Intercept to get the actual Hounsfield Units (HU) for CT images, for instance.\n\n* HU is very important in diagnostic radiology. Differential diagnosis may vary by the HU value of a mass/collection. For more information check this radiopaedia article [here](http://https://radiopaedia.org/articles/hounsfield-unit?lang=us).\n\n* The HU calculation formula is: \n#### HU Value = (Pixel Value× RescaleSlope) + RescaleIntercept\n","metadata":{}},{"cell_type":"code","source":"# Convert to Hounsfield units\npixel_array_hu = ds.pixel_array * ds.RescaleSlope + ds.RescaleIntercept\n\nplt.imshow(pixel_array_hu, cmap='gray')\nplt.axis('off')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T01:53:15.402801Z","iopub.execute_input":"2023-10-08T01:53:15.403185Z","iopub.status.idle":"2023-10-08T01:53:15.533367Z","shell.execute_reply.started":"2023-10-08T01:53:15.403158Z","shell.execute_reply":"2023-10-08T01:53:15.531971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 9. Reading a DICOM Series\n* DICOM series are sets of related images, usually representing different slices of a 3D volume. Reading them in a sorted manner is crucial for correct interpretation and further processing like 3D reconstruction.","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\n\n# Specify the directory path where the DICOM series is stored\ndicom_series_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057'\n\ndicom_file_names = [f for f in os.listdir(dicom_series_path) if os.path.isfile(os.path.join(dicom_series_path, f))]\n\n\n# List and read all DICOM files in the directory\ndicom_files = [pydicom.dcmread(os.path.join(dicom_series_path, f)) for f in dicom_file_names]\n\ndicom_files.sort(key=lambda x: int(x.InstanceNumber)) # You may want to sort all the images.\n\n\n# You can then compile these slices into a 3D NumPy array if needed. \n# This is often useful for 3D visualization or volume-based analysis.\n\n# Initialize an empty 3D NumPy array\nvolume_shape = (len(dicom_files), dicom_files[0].Rows, dicom_files[0].Columns)\nvolume_3d = np.zeros(volume_shape, dtype=np.int16)\n\n# Fill the 3D array with the pixel arrays from each DICOM file\nfor i, ds in enumerate(dicom_files):\n    volume_3d[i, :, :] = ds.pixel_array\n","metadata":{"execution":{"iopub.status.busy":"2023-10-08T02:18:06.045309Z","iopub.execute_input":"2023-10-08T02:18:06.045688Z","iopub.status.idle":"2023-10-08T02:18:17.35904Z","shell.execute_reply.started":"2023-10-08T02:18:06.04564Z","shell.execute_reply":"2023-10-08T02:18:17.358097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# You can visualize the 3D Volume\n\nfig, ax = plt.subplots(nrows= 3, ncols= 3)\nax = ax.ravel()\n\nfor i,j in enumerate(np.linspace(0,volume_3d.shape[0]-1,num= 9, dtype = int)):\n    plt.sca(ax[i])\n    plt.axis('off')\n    plt.imshow(volume_3d[j], cmap = 'gray')\n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-08T02:27:39.277182Z","iopub.execute_input":"2023-10-08T02:27:39.277538Z","iopub.status.idle":"2023-10-08T02:27:39.738056Z","shell.execute_reply.started":"2023-10-08T02:27:39.277511Z","shell.execute_reply":"2023-10-08T02:27:39.736834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 10. Decompressing Compressed DICOM Files\n* Some DICOM files are stored in a compressed format to save space. Before processing these files, you may need to decompress them. The decompress method in pydicom can handle this for you.","metadata":{}},{"cell_type":"code","source":"# Decompress the DICOM file\nds.decompress()","metadata":{"execution":{"iopub.status.busy":"2023-10-08T02:29:43.179586Z","iopub.execute_input":"2023-10-08T02:29:43.180451Z","iopub.status.idle":"2023-10-08T02:29:43.185776Z","shell.execute_reply.started":"2023-10-08T02:29:43.180414Z","shell.execute_reply":"2023-10-08T02:29:43.18452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Finale! I hope you enjoyed this notebook.\n\n    With this guide, you may have an understanding of how to perform essential operations on DICOM files using pydicom. Whether you're a novice or have some experience, these examples should serve as a solid foundation for your projects involving medical imaging. If you enjoyed the guide, upvotes are appreciated. Thanks!!","metadata":{}}]}