<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aykhan.py on Medium]]></title>
        <description><![CDATA[Stories by Aykhan.py on Medium]]></description>
        <link>https://medium.com/@a.turlasov?source=rss-21fea26dc4c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oAv3ieL2unn_ny16.jpg</url>
            <title>Stories by Aykhan.py on Medium</title>
            <link>https://medium.com/@a.turlasov?source=rss-21fea26dc4c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:56:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.turlasov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Preprocessing of medical images in DICOM format]]></title>
            <link>https://medium.com/@a.turlasov/preprocessing-of-medical-images-in-dicom-format-87868e1f2ad9?source=rss-21fea26dc4c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/87868e1f2ad9</guid>
            <category><![CDATA[medical-imaging]]></category>
            <dc:creator><![CDATA[Aykhan.py]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 12:09:57 GMT</pubDate>
            <atom:updated>2022-12-16T12:09:57.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is DICOM</h3><p>When it comes to medical images there is nothing familiar with casual photos that we used to see on our screens, computers, and smartphones. Ordinary images often have 3 or 4 channels — RGB or RGBA and each pixel has a value between 0 and 255 e.g. 8 bits per array element. However, with X Rays or CTs, we encounter monochrome images scaled in HU units and here we will try to understand how to work with this format.</p><p>Here as an example, I will use one of the DICOM files from <a href="https://www.kaggle.com/competitions/rsna-str-pulmonary-embolism-detection">RSNA STR Pulmonary Embolism Detection</a>.</p><h3>How to open an image</h3><p>Before we start here are all the libraries that we need</p><pre>import numpy as np<br>import pydicom<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>The first thing that we usually do is try to visualize the image. As it is written in the title we will use pydicom library.</p><pre>dicom = pydicom.read_file(path_to_dicom)<br>print(dicom)</pre><pre>Dataset.file_meta -------------------------------<br>(0002, 0000) File Meta Information Group Length  UL: 202<br>(0002, 0001) File Meta Information Version       OB: b&#39;\x00\x01&#39;<br>(0002, 0002) Media Storage SOP Class UID         UI: CT Image Storage<br>(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.840.113654.2.70.1.19541131400947984608993616741975715759.1<br>(0002, 0010) Transfer Syntax UID                 UI: Implicit VR Little Endian<br>(0002, 0012) Implementation Class UID            UI: 1.2.826.0.1.3680043.8.498.1<br>(0002, 0013) Implementation Version Name         SH: &#39;PYDICOM 1.2.2&#39;<br>-------------------------------------------------<br>(0008, 0005) Specific Character Set              CS: &#39;ISO_IR 100&#39;<br>(0008, 0008) Image Type                          CS: &quot;[&#39;ORIGINAL&#39;, &#39;PRIMARY&#39;, &#39;AXIAL&#39;]&quot;<br>(0008, 0016) SOP Class UID                       UI: 80e30f500244<br>(0008, 0018) SOP Instance UID                    UI: 73be1ea43642<br>(0008, 0060) Modality                            CS: &#39;CT&#39;<br>(0018, 0050) Slice Thickness                     DS: &#39;1.25&#39;<br>(0018, 0060) KVP                                 DS: &#39;120.0&#39;<br>(0018, 1120) Gantry/Detector Tilt                DS: &#39;0.0&#39;<br>(0018, 1130) Table Height                        DS: &#39;133.0&#39;<br>(0018, 1140) Rotation Direction                  CS: &#39;CW&#39;<br>(0018, 1151) X-Ray Tube Current                  IS: &#39;343&#39;<br>(0018, 1152) Exposure                            IS: &#39;192&#39;<br>(0018, 1210) Convolution Kernel                  SH: &#39;B&#39;<br>(0018, 5100) Patient Position                    CS: &#39;FFS&#39;<br>(0020, 000d) Study Instance UID                  UI: 9da4269a24ed<br>(0020, 000e) Series Instance UID                 UI: 844a3e127a11<br>(0020, 0011) Series Number                       IS: &#39;2&#39;<br>(0020, 0013) Instance Number                     IS: &#39;642&#39;<br>(0020, 0032) Image Position (Patient)            DS: [-178.5, -56.5, -223.95]<br>(0020, 0037) Image Orientation (Patient)         DS: [1, 0, 0, 0, 1, 0]<br>(0020, 0052) Frame of Reference UID              UI: 208030a8292d<br>(0028, 0002) Samples per Pixel                   US: 1<br>(0028, 0004) Photometric Interpretation          CS: &#39;MONOCHROME2&#39;<br>(0028, 0010) Rows                                US: 512<br>(0028, 0011) Columns                             US: 512<br>(0028, 0030) Pixel Spacing                       DS: [0.697265625, 0.697265625]<br>(0028, 0100) Bits Allocated                      US: 16<br>(0028, 0101) Bits Stored                         US: 12<br>(0028, 0102) High Bit                            US: 11<br>(0028, 0103) Pixel Representation                US: 0<br>(0028, 1050) Window Center                       DS: [00040, 00040]<br>(0028, 1051) Window Width                        DS: [00400, 00400]<br>(0028, 1052) Rescale Intercept                   DS: &#39;-1024.0&#39;<br>(0028, 1053) Rescale Slope                       DS: &#39;1.0&#39;<br>(7fe0, 0010) Pixel Data                          OW: Array of 524288 elements</pre><p><em>pydicom.read_file</em> takes a path to a file and returns a so-called FileDataset — pydicom’s class for handling the DICOM images.<br>After printing dicom variable you can see metadata. However, we seek a NumPy matrix that can be visualized by matplotlib. Here is how we get it.</p><pre>img = dicom.pixel_array<br>plt.imshow(img, cmap=&#39;bone&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*UEavrPUtOZTueqsO" /><figcaption>Raw image.</figcaption></figure><p>Let&#39;s print a histogram of our file.</p><pre>sns.histplot(img.flatten())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*Hb7rPS2FQDKfBKIV" /><figcaption>Histogram of values of raw image</figcaption></figure><p>As you can see, the data is not on an 8-bit scale. Let’s understand how to work with such numbers.</p><h3>Hounsfield scale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C6jEU55ljIjUSgdr" /><figcaption>HU mapping to tissues.</figcaption></figure><p>Medical images are usually scaled in so-called Hounsfield units (HU). HU does not have value restrictions as ordinary images from 0 to 255, however, they usually lie between -3000 and 3000. Greater the value the greater the density. You can see a mapping of different tissues to HU above.</p><p>But if we take a look at our histogram, we can see, that our initial pixel array has a minimum value of 0, but HU also has values below 0. This is because some tomographs linearly rescale images to make file weight lighter. So we need to scale it back to HU units. Here is where we need DICOM metadata. We need to access RescaleSlope and RescaleIntercept tags. This is a function that rescales it back.</p><pre>def rescale_dicom(dicom: pydicom.dataset.FileDataset) -&gt; np.ndarray:<br>    img = dicom.pixel_array<br>    img = int(dicom.RescaleSlope) * img + int(dicom.RescaleIntercept)<br>    return img</pre><p>Since the slope in our example is 1, no multiplication is applied. However, the intercept equals -1024, thus, our pixel array is shifted up to 1024.</p><h3>Windowing</h3><p>Since HU can hold more information than ordinary images, we can benefit from this by choosing the window of values to display. For example, if we need to focus only on soft tissues rather than on the lungs we can visualize only values between -200 and 400. Below is the ready-to-use function to apply windowing for the lungs.</p><pre>def apply_window(img: np.ndarray, window_level: int, window_width: int) -&gt; np.ndarray:<br>    upper = window_level + window_width // 2 <br>    lower = window_level - window_width // 2<br>    windowed_img = np.clip(img.copy(), lower, upper)<br>    windowed_img = windowed_img - np.min(windowed_img)<br>    windowed_img = windowed_img / np.max(windowed_img)<br>    windowed_img = (windowed_img * 255.0).astype(&#39;uint8&#39;)<br>    return windowed_img</pre><p>Basically, the function takes 3 parameters — image in HU, window_level — the center of the window, widnow_width — range of visualization. So if we pass window_level = 100 and window_width = 600 the function will focus on values between [100 — (600/2); 100 + (600/2)] e.g. -200 and 400. values that are out of these bounds will be clipped. The resultant array is then rescaled to the 8-bit image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yylLrtyozXUj3c1W" /><figcaption>Visualization of the window that will be applied</figcaption></figure><p>Let’s visualize the result</p><pre>windowed_img = apply_window(img, window_level=100, window_width=600)<br>plt.imshow(windowed_img, cmap=&#39;bone&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*jB13TNgAxcKNJxIf" /><figcaption>CT image with applied windowing.</figcaption></figure><p>Here we see no lungs and can focus on soft tissues. Below you can see other useful windowings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*IIZomR8oGWQFBq0o" /><figcaption>WL — window level, WW — window width.</figcaption></figure><h3>Overview</h3><p>So let’s review the steps of DICOM image preprocessing:<br>1. Reading DICOM file from a path.<br>2. Reading pixel_array.<br>3. Rescaling pixel_array to HU.<br>4. Applying windowing for a better view and getting rid of unnecessary information.<br>After these steps you will get an array, that can be then used for training CNN or any other purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87868e1f2ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>