<?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 Omar Alkousa on Medium]]></title>
        <description><![CDATA[Stories by Omar Alkousa on Medium]]></description>
        <link>https://medium.com/@omar.ok1998?source=rss-f8302b9534b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cbt2OZmjK3JVdDQMKnYj0g.jpeg</url>
            <title>Stories by Omar Alkousa on Medium</title>
            <link>https://medium.com/@omar.ok1998?source=rss-f8302b9534b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:46:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omar.ok1998/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[Reference Management Using Mendeley.]]></title>
            <link>https://medium.com/@omar.ok1998/reference-management-using-mendeley-ed9b26a20767?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9b26a20767</guid>
            <category><![CDATA[mendeley]]></category>
            <category><![CDATA[research-tools]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[reference-management]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 10:34:49 GMT</pubDate>
            <atom:updated>2023-09-23T19:05:03.736Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of academic research, the ability to effectively manage references and citations is crucial. Scholars and researchers often find themselves overwhelmed with numerous sources, making it challenging to keep track of the information they gather. However, thanks to the revolutionary Mendeley software package, this cumbersome task has become significantly easier with Reference Management software packages. In this post, we will explore how Mendeley, a reference manager, is one of the most important tools for researchers, empowering them to efficiently manage references and citations while streamlining their research process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3BbhUP2PARUjkGaK" /><figcaption>Photo by <a href="https://unsplash.com/@gulfergin_01?utm_source=medium&amp;utm_medium=referral">Gülfer ERGİN</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Contents</h3><ul><li>What is a reference? What is a citation?</li><li>What is reference management? Why use it?</li><li>Getting started with Mendeley</li><li>Collecting References</li><li>Organizing References</li><li>Cite while you write using Mendeley Cite in MS Word</li></ul><h3>What is a reference? What is a Citation?</h3><p>“A reference gives the readers details about the source so that they have a good understanding of what kind of source it is and could find the source themselves if necessary” <a href="https://labwrite.ncsu.edu/res/res-citsandrefs.html">[1]</a></p><p>“A citation tells the readers where the information came from. In your writing, you cite or refer to the source of information” <a href="https://labwrite.ncsu.edu/res/res-citsandrefs.html">[1]</a></p><p>Ideally, a research paper will contain two types of information. The first is the researchers’ thoughts. The second type is the information that the researcher depends on from other sources.</p><p>The researcher <strong>must always cite</strong> all the sources he relied on while writing the paper, whether the information was directly quoted or paraphrased.</p><p>There are many styles of citations. Examples are APA, MLA, Chicago, and IEEE. The research has to cite all the sources in only one of the styles in the paper.</p><h3>What is reference management? and why use it?</h3><p>Reference management is the process of <strong>collecting, organizing, and citing research sources</strong> such as articles, books, and websites in a systematic manner. <a href="https://library-guides.ucl.ac.uk/reference-management-software">[2]</a></p><p>Although the researcher can cite and write a list of references manually without using a reference manager, it will take so much time and effort. The figure below represents the advantages of using reference management software in comparison to manual referencing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oo93-RV7PSr55pNgqrWqw.png" /><figcaption>The advantages of using a reference manager. [Image by the author]</figcaption></figure><p>Now that we have a clear understanding of what references and citations are, let’s discuss the workflow of reference management We will learn each step of managing our references using Mendeley software <strong>(collecting, organizing, and citing)</strong>. Although <a href="https://endnote.com/?language=en"><strong>EndNote</strong></a> and <a href="https://www.zotero.org/"><strong>Zotero</strong></a> are other software options for managing references, I prefer Mendeley because it is free and has excellent features.</p><h3>Mendeley Reference Manager</h3><p>Mendeley Reference Manager is a free web and desktop reference management application. It helps you simplify your reference management workflow.</p><h4>Getting started with Mendeley</h4><p>A great tutorial to get started with Mendeley is the video by <a href="https://www.youtube.com/watch?v=OzFHGFnAM2Q&amp;t=5s&amp;pp=ygUIbWVuZGVsZXk%3D">Steven Bradburn.</a></p><p>Basic Steps you can follow:</p><ul><li><a href="https://www.mendeley.com/download-reference-manager/windows">Download</a> the proper version of Mendeley on your Computer.</li><li>Go to <a href="https://www.mendeley.com/join/">mendeley.com</a> to create an account.</li><li>Add the <a href="https://www.mendeley.com/reference-management/web-importer">Web Importe</a><a href="http://www.mendeley.com/reference-management/web-importer">r</a> to your browser.</li><li>Add the tool <a href="https://appsource.microsoft.com/en-us/product/office/wa104382081?tab=overview">Mendeley Cite</a> to your Microsoft Word.</li></ul><p>Let’s start learning how to import references into our Library…</p><h3>Collecting References</h3><p>There are many different ways to import a reference into your Mendeley library:</p><ul><li>Using the Mendeley Web Importer tool</li><li>Using identifiers (DOI, PMID, ArXivID)</li><li>Using Google Scholar Citation</li><li>Manually add the source (Web pages)</li></ul><h4>Import a reference using the Web Importer tool</h4><p>Mendeley provides a browser extension that helps the researcher to connect with his Mendeley library. With this tool, you can add any source you’re reading on your browser to your library. The video below represents how to do this using the <a href="https://www.sciencedirect.com/science/article/abs/pii/B9780128093955000023?via%3Dihub">second chapter</a> of the book “Circuits, Signals and Systems for Bioengineers (Third Edition)” as an example</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlKJLk1CvIG0%3Flist%3DPL2_7bpOFGW3B-CQMU-TjS0Wuj3Ugz2IiO&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlKJLk1CvIG0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlKJLk1CvIG0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/57377700a43449e43f94897b315431f5/href">https://medium.com/media/57377700a43449e43f94897b315431f5/href</a></iframe><h4>Import references using identifiers</h4><p>Usually, a research paper has its identifier to allow easier access to the sources. One of the most famous identifiers is the Digital Object Identifier (DOI). Other examples are PubMed Identifier (PMID) and ArXiv Identifier (ArXivID). We can use these identifiers to easily import the source into our Mendeley library. The video below shows how to import a reference using DOI.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXYSUgW81Ll4%3Flist%3DPL2_7bpOFGW3B-CQMU-TjS0Wuj3Ugz2IiO&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXYSUgW81Ll4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXYSUgW81Ll4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a49e505c51eb643ccdff150261c86a/href">https://medium.com/media/76a49e505c51eb643ccdff150261c86a/href</a></iframe><h4>Import a reference using Google Scholar Citation</h4><p><a href="https://scholar.google.com/">Google Scholar</a> provides a wide range of disciplines and sources, making it a comprehensive resource for academic research. It also offers features such as citation metrics, alerts for new publications, and the ability to save articles to a personal library. One of the useful features provided by Google Scholar is “Cite”, which allows the researchers to get the right citation of the resources.</p><p>This “Cite” feature provides the citation in many styles. Moreover, it allows to download the citation as a file for further use in reference management software. The video is represented below to learn how to use Cite from Google Scholar to add a source to Mendeley Library.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6vwfkO8UuQk%3Flist%3DPL2_7bpOFGW3B-CQMU-TjS0Wuj3Ugz2IiO&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6vwfkO8UuQk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6vwfkO8UuQk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5001254b810355896fb93e2fa173cd55/href">https://medium.com/media/5001254b810355896fb93e2fa173cd55/href</a></iframe><h4>Manually add the source (Web pages)</h4><p>Often, a resource has no Identifier or citation on Google Scholar. An example is a web page. In this case, we need to manually import the information of the resource into the Mendeley library.</p><p>The video below shows how you can manually import a web page as a resource.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Feyrn_eMKFI4%3Flist%3DPL2_7bpOFGW3B-CQMU-TjS0Wuj3Ugz2IiO&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Deyrn_eMKFI4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Feyrn_eMKFI4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8838568c85df7d0eb67caab8046c3371/href">https://medium.com/media/8838568c85df7d0eb67caab8046c3371/href</a></iframe><h3>Organizing References</h3><p>Now that we’ve learned how to import any resource we want, it’s time to categorize and organize them. Mendeley allows users to create their collections to categorize each reference they import into their library. This is useful if you have multiple subjects you are interested in.</p><p>The video below is to learn how to create a new collection in Mendeley and how to add specific references to it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAvE0Y3i65Kw&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAvE0Y3i65Kw&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FAvE0Y3i65Kw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f956285f140fa5ea1f68d19ef2bf2999/href">https://medium.com/media/f956285f140fa5ea1f68d19ef2bf2999/href</a></iframe><h3>Cite while you write using Mendeley Cite MS Word</h3><p>After collecting and organizing your references, your job with Mendeley is done. Now you can write your paper and cite your work easily using the tool Mendeley provides that allows connecting to Mendeley library. Add the tool <a href="https://appsource.microsoft.com/en-us/product/office/wa104382081?tab=overview">Mendeley Cite</a> to your Microsoft Word. The video below represents how to use this tool to cite your work, update the citations and the references, and change the citation style.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FelHxWS383PE%3Flist%3DPL2_7bpOFGW3B-CQMU-TjS0Wuj3Ugz2IiO&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DelHxWS383PE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FelHxWS383PE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed9a7fd2a6f5ca912e45af1885ea25b1/href">https://medium.com/media/ed9a7fd2a6f5ca912e45af1885ea25b1/href</a></iframe><blockquote>Have fun researching and citing…</blockquote><h3>Recourses</h3><p>[<a href="https://labwrite.ncsu.edu/res/res-citsandrefs.html">1</a>] “Citations and References,” <em>North Carolina State University — LabWrite Resources</em>, 2004. <a href="https://labwrite.ncsu.edu/res/res-citsandrefs.html">https://labwrite.ncsu.edu/res/res-citsandrefs.html</a> (accessed Sep. 09, 2023).</p><p>[<a href="https://library-guides.ucl.ac.uk/reference-management-software">2</a>] “What is reference management software,” <em>University College London</em>, Sep. 07, 2023. <a href="https://library-guides.ucl.ac.uk/reference-management-software">https://library-guides.ucl.ac.uk/reference-management-software</a> (accessed Sep. 09, 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9b26a20767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensemble Averaging in Medical Signal Processing]]></title>
            <link>https://medium.com/data-science/ensemble-averaging-in-medical-signal-processing-17116d0cf0d2?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/17116d0cf0d2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[signal-processing]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Tue, 02 May 2023 06:04:26 GMT</pubDate>
            <atom:updated>2023-05-02T06:04:26.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple yet so powerful method</h4><p>Dealing with data as a researcher, a data scientist/analyst, or even in any science field is inevitable. Thus, the reliability of the data you’re working with is crucial as it decides the reliability of your work.</p><p>In this post, we will introduce the ensemble averaging method, a simple but powerful method, and its applications on signal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UxmLS3mFc86Iq1Y7" /><figcaption>Photo by <a href="https://unsplash.com/@chesnutt?utm_source=medium&amp;utm_medium=referral">Eran Menashri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>The average is a single value that can describe a set of values. It can be defined as the sum of the variables divided by the number of variables. If we have a set of variables {x1, x2, …, xn}, the average can be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*AHrurgZgqHhNy7rqKOwTbw.png" /></figure><p>A simple example you can think of to introduce the idea of ensemble averaging is measuring the temperature of a solution that has a stable temperature during the measurement. An electronic sensor can be used to measure the temperature three times for a time of ten seconds. the ensemble averaging can be done by taking the average of the three measurements.</p><p>From the example above, the ensemble averaging method requires the ability to repeat the experiment you are conducting with the same properties of the measurement system [<a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3">1</a>]. This is hard to be applied in many real-world cases. Therefore, a solution that might be considered in many cases is conducting the experiment one time but using multiple sensors [<a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3">1</a>] simultaneously to produce multiple observations of the corresponding experiment.</p><p>In the case of the signal type of data (time series), the ensemble averaging method is done by averaging the samples of the signals point-by-point [<a href="https://www.ijarcce.com/upload/2016/august-16/IJARCCE%2052.pdf">2</a>]. Therefore, a prerequisite before applying the method is that the signals generated are aligned in time [<a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3">1</a>]. Below is an illustration of applying ensemble averaging on signal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*89qBX3Y7gIKT_u454H6x2Q.png" /><figcaption>Applying the ensemble averaging method using two experiments. Notice the samples of the signal are aligned in time. [Image by the Author]</figcaption></figure><h3>Why use the ensemble averaging method? Why do we repeat experiments?</h3><p>The first time I got into ensemble averaging was at the biomechanics lab, which is specialized in studying gait patterns and analyzing human locomotion. When my professor instructed to conduct the experiment on the same patient to get at least three successful experiments, <strong>I asked why three times and not just one successful experiment?!</strong><br>The answer was to calculate the ensemble average of these three experiments to get the final signal with higher reliability and less prone to random noise.</p><p>In common sense, repeating the experiments ensure that the data you obtain is the data of interest. But of course, the cost and the time of experiment repetitions have to be considered.</p><p>From a signal-processing perspective, ensemble averaging has many advantages in enhancing the signal data. These advantages can be concluded as follows:</p><ul><li>Ensemble averaging is useful for filtering random noise in the signals [<a href="https://www.ijarcce.com/upload/2016/august-16/IJARCCE%2052.pdf">2</a>].</li><li>Applying the ensemble averaging method improves the Signal to Noise Ratio (SNR). If we have N number of repetitions, the improvement is proportional to the square root of N [<a href="https://www.ijarcce.com/upload/2016/august-16/IJARCCE%2052.pdf">2</a>].</li></ul><h3>Real-world Medical Example</h3><p>The applications of the ensemble averaging method are limitless. A great example in the medical field is the idea behind Visual Evoked Response/Potential test (VER or VEP test). The aim of this test is to measure the response to visual stimulation which is produced as electrical signals in the visual cortex of the brain. The test depends on the repetitive stimulation with specified timing [<a href="https://eyewiki.aao.org/Visual_Evoked_Potential/_Response_(VEP/VER)">3</a>]. The visual stimulation is done using a screen black-white checkerboard [<a href="https://eyewiki.aao.org/Visual_Evoked_Potential/_Response_(VEP/VER)">3</a>]. The repetitive stimuli’s signals are averaged point-by-point (ensemble average) to determine the VER signal [<a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3">1</a>], remember that the signals are aligned in time of the stimulation process. The following is an example of how to extract VER signals using the ensemble averaging method.</p><p>The signal data we will use are available following this <a href="https://github.com/Roshni1999/John-Semmlow-Signals-and-Systems-for-Bioengineers-2ed/blob/9c6efc1c68e042212cff45a5fb41902d6699a09e/Chapter1/ver.mat"><strong>link</strong></a> (MIT Licensed). The data consists of 100 electrical signals recorded at 200 Hz of sampling rate.</p><h3>Ensemble Averaging using Python</h3><p>First, we will import the required Python packages:</p><ul><li><strong>Numpy</strong>: for array manipulation and arithmetic calculation.</li><li><strong>Matplotlib</strong>: to visualize the signal data of the VER response.</li><li><strong>Scipy</strong>: we will use the module scipy.io to read the data file (.MAT file type).</li></ul><pre># Import the required packages<br>import matplotlib.pyplot as plt<br>import numpy as np<br>from scipy import io</pre><p>Now, we read the data file that contains the electrical signals using the <em>scipy.io.loadmat</em> method. The output is a dictionary of the file content. The electrical signals can be found in the item “ver”.</p><pre># Read a Mat file using scipy.io<br>mat = io.loadmat(&#39;ver.mat&#39;)<br># Exract the electrical signals<br>ver = mat[&#39;ver&#39;]</pre><p>Let’s explore the size of the data we are working with.</p><pre># The size of variable &quot;ver&quot;<br>print(ver.shape)</pre><pre>(100, 500)</pre><p>This means that we have 100 signals and each one has 500 samples. Applying the ensemble averaging method to this data will average 100 signals and produce one signal with 500 samples.</p><p>After extracting the signal data, we will define the sampling rate the generate the time axis of the signals.</p><pre># Calculate the sampling rate<br>sampling_rate = 200.0<br># Calculate the duration of the recordings<br>duration = ver.shape[1]/sampling_rate<br># Generate the time axis of the recordings<br>time_axis = np.arange(0, duration, 1/sampling_rate)</pre><p>Now that we have the time axis and the signals we are studying, we can visualize some of the signals along the same time axis to see what the single visual response looks like. We will visualize only the first 10 signals.</p><pre># Subplot figure with 10 rows and one column<br>fig, axs = plt.subplots(10, figsize=(10,5), sharex=True)<br><br># Plot the first 10 recordings<br>for i in range(10):<br>    axs[i].plot(time_axis, ver[i,:])<br>    # Hide the values of y-axis<br>    axs[i].set_yticks([])<br>    # Fit the x-axis along the signal<br>    axs[i].set_xlim([time_axis[0], time_axis[-1]])<br><br># Set a title and xlabel<br>axs[0].set_title(&#39;The first 10 Signals&#39;)<br>axs[9].set_xlabel(&#39;Time [Sec]&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*VIscao4ITb5PthDetp67TA.png" /><figcaption>The first 10 signals of the data. [Image by the Author]</figcaption></figure><p>Notice that we cannot recognize the visual response from only one signal. Therefore, we’re going to use ensemble averaging to determine the VER.</p><pre># Apply the ensamble averaging method on the Recordings.<br>ver_signal = np.mean(ver, axis=0)<br># Extract the actual VER from the Mat file<br>actual_ver = np.reshape(mat[&#39;actual_ver&#39;], [500])<br><br># Plot the ensambled EEG recordings and the actual VER<br>plt.plot(time_axis, ver_signal, color=&#39;green&#39;, label=&#39;Ensamble Averaging&#39;)<br>plt.plot(time_axis, actual_ver, color=&#39;red&#39;, label=&#39;Actual VER&#39;)<br>plt.xlim([time_axis[0], time_axis[-1]])<br>plt.xlabel(&#39;Time [sec]&#39;)<br>plt.ylabel(&#39;Average&#39;)<br>plt.title(&#39;Visual Evoked Response&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ezlX7bEWfwBRdlB_KhfP3g.png" /><figcaption>VER using ensemble averaging on 100 signals. [Image by the Author]</figcaption></figure><h3>Conclusion</h3><ul><li>We’ve introduced Ensemble Averaging, a simple yet very helpful method that you can use to extract reliable data.</li><li>We’ve pointed out the reason behind repeating experiments and how it enhances the reliability of the data.</li><li>Applying ensemble averaging improves the SNR of the signal by the square root of the N (the number of repetitions). Also, the final signal data are less prone to random noise.</li><li>We’ve introduced an example using the ensemble averaging method to determine the Visual Evoked Response (VER) based on repetitive stimulation with specified timing.</li></ul><h3>References</h3><p><strong>[</strong><a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3"><strong>1</strong></a><strong>]</strong> Semmlow, J. (2018). Signal Analysis in the Time Domain. In <em>Circuits, Signals and Systems for Bioengineers</em> (pp. 51–110). Elsevier. <a href="https://doi.org/10.1016/B978-0-12-809395-5.00002-3">https://doi.org/10.1016/B978-0-12-809395-5.00002-3</a></p><p><strong>[</strong><a href="https://www.ijarcce.com/upload/2016/august-16/IJARCCE%2052.pdf"><strong>2</strong></a><strong>]</strong> Thomas, T. (2005). Ensemble Averaging Filter for Noise Reduction. <em>International Journal of Advanced Research in Computer and Communication Engineering</em>, <em>5</em>(8).</p><p><strong>[</strong><a href="https://eyewiki.aao.org/Visual_Evoked_Potential/_Response_(VEP/VER)"><strong>3</strong></a><strong>]</strong> Tripathy, K., Hsu, J., &amp; Lim, J. (2022, November 10). <em>Visual Evoked Potential/ Response (VEP/VER). </em>American Academy of Ophthalmology. <a href="https://eyewiki.aao.org/Visual_Evoked_Potential/_Response_(VEP/VER)">https://eyewiki.aao.org/Visual_Evoked_Potential/_Response_(VEP/VER)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17116d0cf0d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ensemble-averaging-in-medical-signal-processing-17116d0cf0d2">Ensemble Averaging in Medical Signal Processing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fourier Transform, the Practical Python Implementation]]></title>
            <link>https://medium.com/data-science/fourier-transform-the-practical-python-implementation-acdd32f1b96a?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/acdd32f1b96a</guid>
            <category><![CDATA[healthcare-data]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 15:32:42 GMT</pubDate>
            <atom:updated>2023-03-13T11:57:46.064Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical application on real-world signals</h4><p>Fourier Transform is one of the most famous tools in signal processing and analysis of time series. The Fast Fourier Transform (FFT) is the practical implementation of the Fourier Transform on Digital Signals. FFT is considered one of the top 10 algorithms with the greatest impact on science and engineering in the 20th century <a href="https://doi.ieeecomputersociety.org/10.1109/MCISE.2000.814652"><strong>[1]</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6BAf6q6ifnvLaqWe" /><figcaption>Photo by <a href="https://unsplash.com/@edznorton?utm_source=medium&amp;utm_medium=referral">Edz Norton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, a practical approach to FFT has been discussed as how to use it to represent the frequency domain (spectrum) of the signal data and plot the spectrum using Plotly to give us more interactivity and a better understanding of the features in the spectrum. By the end of this post, we’ll build a class to analyze the signal. An ECG signal and its spectrum have been provided as a final example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fcyMD7PLDnGY3zQW2AJDnw.gif" /><figcaption>Representation of using our class Fourier. [Image by the Author]</figcaption></figure><h3>Introduction</h3><p>Fourier Transform (FT) relates the time domain of a signal to its frequency domain, where the frequency domain contains the information about the sinusoids (amplitude, frequency, phase) that construct the signal. Since FT is a continuous transform, the Discrete Fourier Transform (DFT) becomes the applicable transform in the digital world that holds the information of signals in the discrete format as a set of samples, where the sampling theorem is the strict rule of discretizing and the signal. The DFT of a signal (xn) with N number of samples is given by the following equation <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[2]</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*I0DSjtq8h-kRB8HW.png" /><figcaption>The DFT equation <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html">[2]</a></figcaption></figure><p><strong>Where:</strong></p><ul><li>N: Number of samples</li><li>n: Current sample</li><li>k: Current frequency where k∈[0,N−1]</li><li>xn: The sine value at sample n</li><li>Xk: The DFT which includes information on both amplitude and phase</li></ul><p>The output of the DFT (Xk) is an array of complex numbers that hold the information of frequency components <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[2]</strong></a>. Applying DFT on signals using the mathematical equation directly demands a heavy computation complexity. Luckily, a Fast Fourier Transform (FFT) was developed <a href="https://www.ams.org/journals/mcom/1965-19-090/S0025-5718-1965-0178586-1/"><strong>[3]</strong></a> to provide a faster implementation of the DFT. The FFT takes advantage of the symmetry nature of the output of the DFT. We will not further discuss how FFT works as it’s like the standard practical application of DFT. But if you want more details, refer to <a href="https://www.ams.org/journals/mcom/1965-19-090/S0025-5718-1965-0178586-1/"><strong>[3]</strong></a>.</p><h3>Let’s Code:</h3><p>We will start simply to understand the inputs and outputs of each method we use in this post. First, we will import the required packages. Numpy is for dealing with matrices and calculations. We import the methods that help us with the calculations related to Fourier Analysis from scipy.fft module (fft, rfft, fftfreq, rfftfreq). Finally, Plotly and matplotlib are for visualization.</p><h4>Let’s get started…</h4><pre># Import the required packages<br>import numpy as np<br>from scipy.fft import fft, rfft<br>from scipy.fft import fftfreq, rfftfreq<br>import plotly.graph_objs as go<br>from plotly.subplots import make_subplots<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><p>We need signals to try our code on. Sinusoids are great and fit to our examples. In the next code, we generate a sinusoidal signal using a class named Signal, which you can find ready to use following this <a href="https://gist.github.com/OmarAlkousa/4bd0bacb0ff976be4105777965854e06"><strong>GitHub gist</strong></a>. The signal we will generate using the previous class contains three sinusoids (1, 10, 20) Hz with amplitudes of (3, 1, 0.5), respectively. The sampling rate will be 200 and the duration of the signal is 2 seconds.</p><pre># Generate the three signals using Signal class and its method sine()<br>signal_1hz = Signal(amplitude=3, frequency=1, sampling_rate=200, duration=2)<br>sine_1hz = signal_1hz.sine()<br>signal_20hz = Signal(amplitude=1, frequency=20, sampling_rate=200, duration=2)<br>sine_20hz = signal_20hz.sine()<br>signal_10hz = Signal(amplitude=0.5, frequency=10, sampling_rate=200, duration=2)<br>sine_10hz = signal_10hz.sine()<br><br># Sum the three signals to output the signal we want to analyze<br>signal = sine_1hz + sine_20hz + sine_10hz<br><br># Plot the signal<br>plt.plot(signal_1hz.time_axis, signal, &#39;b&#39;)<br>plt.xlabel(&#39;Time [sec]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.title(&#39;Sum of three signals&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*RvuroaYBTHAijwS-MwumwQ.png" /><figcaption>The signal we will process next. [Image by the Author]</figcaption></figure><p>The Fourier Transform of this signal can be calculated using (fft) from the scipy package as follows <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html#scipy.fft.fft"><strong>[4]</strong></a>:</p><pre># Apply the FFT on the signal<br>fourier = fft(signal)<br><br># Plot the result (the spectrum |Xk|)<br>plt.plot(np.abs(fourier))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*B6r45ML9UyzD3pMyVRPVUQ.png" /><figcaption>The output of the FFT of the signal. [Image by the Author]</figcaption></figure><p>The figure above should represent the frequency spectrum of the signal. Notice that the x-axis is the number of samples (instead of the frequency components) and the y-axis should represent the amplitudes of the sinusoids. To get the actual amplitudes of the spectrum, we have to normalize the output of (fft) by N/2 the number of samples.</p><pre># Calculate N/2 to normalize the FFT output<br>N = len(signal)<br>normalize = N/2<br><br># Plot the normalized FFT (|Xk|)/(N/2)<br>plt.plot(np.abs(fourier)/normalize)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.xlabel(&#39;Samples&#39;)<br>plt.title(&#39;Normalized FFT Spectrum&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*8GXBUJUwwHzOAT6zCcRAhA.png" /><figcaption>The output of the FFT after normalizing. [Image by the Author]</figcaption></figure><p>To get the frequency components (x-axis), you can use (fftfreq) from the scipy package. This method needs the number of samples (N) and the sampling rate as input arguments. And it returns a frequency axis with N frequency components <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fftfreq.html#scipy.fft.fftfreq"><strong>[5]</strong></a>.</p><pre># Get the frequency components of the spectrum<br>sampling_rate = 200.0 # It&#39;s used as a sample spacing<br>frequency_axis = fftfreq(N, d=1.0/sampling_rate)<br>norm_amplitude = np.abs(fourier)/normalize<br># Plot the results<br>plt.plot(frequency_axis, norm_amplitude)<br>plt.xlabel(&#39;Frequency[Hz]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.title(&#39;Spectrum&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*evXdSD7PdsFdPVBiKzjq_g.png" /><figcaption>The spectrum with the actual amplitudes and frequency axis. [Image by the Author]</figcaption></figure><p>To understand what happened in the last code, let’s plot only the frequency axis:</p><pre># Plot the frequency axis for more explanation<br>plt.plot(frequency_axis)<br>plt.ylabel(&#39;Frequency[Hz]&#39;)<br>plt.title(&#39;Frequency Axis&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*vfrsdYjzjAcP9Q7IRu-UnA.png" /><figcaption>The frequency axis. [Image by the Author]</figcaption></figure><p>Notice that the frequency array starts at zero. Then, it begins to increase with (d) step by step to reach its maximum (100Hz). After that, it starts from the negative maximum frequency (-100Hz) to increase back again with (d) step by step. The maximum frequency that can hold information from the signal (100Hz) is half of the sampling rate and this is true according to the Sampling Theorem <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[2]</strong></a>.</p><p>Due to the symmetry of the spectrum for the real-value signals, we only focus on the first half of the spectrum <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[2]</strong></a>. The Scipy package provides methods to deal with the Fourier transform of the real-value signals, where it takes advantage symmetry nature of the spectrum. Such methods are (rfft <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.rfft.html#scipy.fft.rfft"><strong>[6]</strong></a>, rfftfreq <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.rfftfreq.html#scipy.fft.rfftfreq"><strong>[7]</strong></a>). These methods are the same as (fft, fftfreq), respectively. By comparing the time execution between (fft) and (rfft) methods on the same signal, you’ll find that (rfft) is a little bit faster. When dealing with real-value signals, which is most likely the case, using (rfft) is the best choice.</p><pre># Calculate the time execution of (fft)<br>print(&#39;Execution time of fft function:&#39;)<br>%timeit fft(signal)<br># Calculate the time execution of (rfft)<br>print(&#39;\nExecution time of rfft function:&#39;)<br>%timeit rfft(signal)</pre><pre>Execution time of fft function:<br>13.5 µs ± 8.3 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)<br><br>Execution time of rfft function:<br>12.3 µs ± 3.55 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)</pre><p>To conclude our discussion about scaling the amplitudes and generating the frequency axis of the spectrum for real-values signal data that have a symmetry nature in their frequency domain, the code below represents the final form of the spectrum (the actual amplitudes on the right frequencies).</p><pre># Plot the actual spectrum of the signal<br>plt.plot(rfftfreq(N, d=1/sampling_rate), 2*np.abs(rfft(signal))/N)<br>plt.title(&#39;Spectrum&#39;)<br>plt.xlabel(&#39;Frequency[Hz]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*Ia_X57UAAS8BJ-sLNs7Wnw.png" /><figcaption>The actual spectrum of the signal. [Image by the Author]</figcaption></figure><p>The figure below helps you understand and memorize how to get each of the frequency axis and the actual amplitudes of the sinusoids that construct the spectrum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*oyjr8YHnokuDg40QUQ6cEA.png" /><figcaption>Take a moment to read each code line as it gives you the actual spectrum of the signal. [Image by the Author]</figcaption></figure><h3>The Final Code</h3><p>Now that we’ve understood the inputs and outputs of each method we used in Fourier analysis, let’s do our final code. We will build a class (Fourier) to make our use of Fourier Transform more convenient and easier to use. The class we need should calculate the DFT of the signal data and intuitively visualize the data. Make sure to read the documentation of the class to understand the use of this class. If you are not familiar with classes in Python and how to build one, refer to this previous <a href="https://medium.com/towards-data-science/use-classes-for-generating-signals-6694d22e9a80"><strong>post</strong></a> about building a class to generate signals.</p><pre># Building a class Fourier for better use of Fourier Analysis.<br>class Fourier:<br>  &quot;&quot;&quot;<br>  Apply the Discrete Fourier Transform (DFT) on the signal using the Fast Fourier <br>  Transform (FFT) from the scipy package.<br><br>  Example:<br>    fourier = Fourier(signal, sampling_rate=2000.0)<br>  &quot;&quot;&quot;<br><br>  def __init__(self, signal, sampling_rate):<br>    &quot;&quot;&quot;<br>    Initialize the Fourier class.<br><br>    Args:<br>        signal (np.ndarray): The samples of the signal<br>        sampling_rate (float): The sampling per second of the signal<br>    <br>    Additional parameters,which are required to generate Fourier calculations, are<br>    calculated and defined to be initialized here too:<br>        time_step (float): 1.0/sampling_rate<br>        time_axis (np.ndarray): Generate the time axis from the duration and<br>                              the time_step of the signal. The time axis is<br>                              for better representation of the signal.<br>        duration (float): The duration of the signal in seconds.<br>        frequencies (numpy.ndarray): The frequency axis to generate the spectrum.<br>        fourier (numpy.ndarray): The DFT using rfft from the scipy package.<br>    &quot;&quot;&quot;<br>    self.signal = signal<br>    self.sampling_rate = sampling_rate<br>    self.time_step = 1.0/self.sampling_rate<br>    self.duration = len(self.signal)/self.sampling_rate<br>    self.time_axis = np.arange(0, self.duration, self.time_step)<br>    self.frequencies = rfftfreq(len(self.signal), d = self.time_step)<br>    self.fourier = rfft(self.signal)<br>    <br>  # Generate the actual amplitudes of the spectrum<br>  def amplitude(self):<br>    &quot;&quot;&quot;<br>    Method of Fourier<br><br>    Returns:<br>        numpy.ndarray of the actual amplitudes of the sinusoids.<br>    &quot;&quot;&quot;<br>    return 2*np.abs(self.fourier)/len(self.signal)<br><br>  # Generate the phase information from the output of rfft  <br>  def phase(self, degree = False):<br>    &quot;&quot;&quot;<br>    Method of Fourier<br><br>    Args:<br>        degree: To choose the type of phase representation (Radian, Degree).<br>                By default, it&#39;s in radian. <br><br>    Returns:<br>        numpy.ndarray of the phase information of the Fourier output.<br>    &quot;&quot;&quot;<br>    return np.angle(self.fourier, deg = degree)<br><br>  # Plot the spectrum<br>  def plot_spectrum(self, interactive=False):<br>    &quot;&quot;&quot;<br>    Plot the Spectrum (Frequency Domain) of the signal either using the matplotlib<br>    package, or plot it interactive using the plotly package.<br><br>    Args:<br>        interactive: To choose if you want the plot interactive (True), or not<br>        (False). The default is the spectrum non-interactive.<br><br>    Retruns:<br>        A plot of the spectrum.<br>    &quot;&quot;&quot;<br>    # When the argument interactive is set to True:<br>    if interactive:<br>      self.trace = go.Line(x=self.frequencies, y=self.amplitude())<br>      self.data = [self.trace]<br>      self.layout = go.Layout(title=dict(text=&#39;Spectrum&#39;,<br>                                         x=0.5,<br>                                         xanchor=&#39;center&#39;,<br>                                         yanchor=&#39;top&#39;,<br>                                         font=dict(size=25, family=&#39;Arial, bold&#39;)),<br>                              xaxis=dict(title=&#39;Frequency[Hz]&#39;),<br>                              yaxis=dict(title=&#39;Amplitude&#39;))<br>      self.fig = go.Figure(data=self.data, layout=self.layout)<br>      return self.fig.show()<br>    # When the argument interactive is set to False:<br>    else:<br>      plt.figure(figsize = (10,6))<br>      plt.plot(self.frequencies, self.amplitude())<br>      plt.title(&#39;Spectrum&#39;)<br>      plt.ylabel(&#39;Amplitude&#39;)<br>      plt.xlabel(&#39;Frequency[Hz]&#39;)<br>  <br>  # Plot the Signal and the Spectrum interactively<br>  def plot_time_frequency(self, t_ylabel=&quot;Amplitude&quot;, f_ylabel=&quot;Amplitude&quot;,<br>                          t_title=&quot;Signal (Time Domain)&quot;,<br>                          f_title=&quot;Spectrum (Frequency Domain)&quot;):<br>    &quot;&quot;&quot;<br>    Plot the Signal in Time Domain and Frequency Domain using plotly.<br><br>    Args:<br>        t_ylabel (String): Label of the y-axis in Time-Domain<br>        f_ylabel (String): Label of the y-axis in Frequency-Domain<br>        t_title (String): Title of the Time-Domain plot<br>        f_title (String): Title of the Frequency-Domain plot <br><br>    Returns:<br>        Two figures: the first is the time-domain, and the second is the<br>                     frequency-domain.<br>    &quot;&quot;&quot;<br>    # The Signal (Time-Domain)<br>    self.time_trace = go.Line(x=self.time_axis, y=self.signal)<br>    self.time_domain = [self.time_trace]<br>    self.layout = go.Layout(title=dict(text=t_title,<br>                                       x=0.5,<br>                                       xanchor=&#39;center&#39;,<br>                                       yanchor=&#39;top&#39;,<br>                                       font=dict(size=25, family=&#39;Arial, bold&#39;)),<br>                            xaxis=dict(title=&#39;Time[sec]&#39;),<br>                            yaxis=dict(title=t_ylabel),<br>                            width=1000,<br>                            height=400)<br>    fig = go.Figure(data=self.time_domain, layout=self.layout)<br>    fig.show()<br>    # The Spectrum (Frequency-Domain)<br>    self.freq_trace = go.Line(x=self.frequencies, y=self.amplitude())<br>    self.frequency_domain = [self.freq_trace]<br>    self.layout = go.Layout(title=dict(text=f_title,<br>                                       x=0.5,<br>                                       xanchor=&#39;center&#39;,<br>                                       yanchor=&#39;top&#39;,<br>                                       font=dict(size=25, family=&#39;Arial, bold&#39;)),<br>                            xaxis=dict(title=&#39;Frequency[Hz]&#39;),<br>                            yaxis=dict(title=f_ylabel),<br>                            width=1000,<br>                            height=400)<br>    fig = go.Figure(data=self.frequency_domain, layout=self.layout)<br>    fig.show()</pre><p>Let’s try our class on the signal above. The input arguments are the real-values signal data (Time Domain) and the sampling rate of this signal.</p><pre># Apply the DFT using the class Fourier<br>fourier = Fourier(signal, sampling_rate=200)<br># Plot the spectrum interactively using the class Fourier<br>fourier.plot_spectrum(interactive=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvYX9hws3lfH44aUs5HrHA.png" /><figcaption>The spectrum of the signal using our class Fourier. If you’re applying the code above, you can get the values interactively by hovering on the blue line. [Image by the Author]</figcaption></figure><h3>The Spectrum of the Electrocardiogram</h3><p>Our final example will be real-world signal data. We will use the class Fourier to plot the time-frequency domains of an electrocardiogram (ECG). The signal is 5 minutes long of the heart’s electrical activity, sampled at 360Hz <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.electrocardiogram.html#scipy.misc.electrocardiogram"><strong>[8]</strong></a>.</p><pre># Import the ECG signal from scipy package<br>from scipy.misc import electrocardiogram<br># Built-in ECG signal<br>ecg = electrocardiogram()<br># DFT using the class Fourier<br>ecg_spectrum = Fourier(signal = ecg, sampling_rate = 360.0)<br># Plot the time-frequency domains of the ECG signal<br>ecg_spectrum.plot_time_frequency(t_title=&quot;ECG Signal&quot;, f_title=&quot;ECG Spectrum&quot;,<br>                                 t_ylabel=&quot;Amplitude[mV]&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fcyMD7PLDnGY3zQW2AJDnw.gif" /><figcaption>ECG signal and its Frequency Spectrum. [Image by the Author]</figcaption></figure><p>The image above represents an example of using the Fourier class we built in this post (An ECG signal and its Frequency Spectrum). The use of the Plotly package allows you to hover over the values of the plot and zoom in/out on the interesting parts so easily.</p><h3>Conclusion</h3><ul><li>We’ve introduced the Discrete Fourier Transform (DFT) mathematically.</li><li>A step-by-step Fourier Analysis coding was discussed. We started by introducing the Fast Fourier Transform (FFT) and the pythonic implementation of FFT to produce the spectrum of the signals.</li><li>We’ve introduced the requirements of normalizing the spectrum to give us the actual amplitudes of the sinusoids. Also, we’ve used one of the scipy.fft helper functions to generate the frequency axis of the spectrum (fftfreq).</li><li>We’ve pointed out the symmetry nature of the Fourier transform and how the spectrum is symmetric around the sampling frequency. And this is what led us to discuss new methods to deal with real-value signal data (rfft, rfftfreq).</li><li>We’ve built a class to easier use the Fourier transform and produce the frequency domain of the signals interactively using the Plotly package.</li></ul><h4>Thanks for Reading ^_^</h4><h3>References</h3><p><a href="https://doi.ieeecomputersociety.org/10.1109/MCISE.2000.814652"><strong>[1]</strong></a> Dongarra, J., &amp; Sullivan, F. (2000). Guest Editors Introduction to the top 10 algorithms. <em>Computing in Science &amp; Engineering</em>, 2(01), 22–23.</p><p><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[2]</strong></a> Kong, Q., Siauw, T., &amp; Bayen, A. (2020). Fourier Transform. <em>Python programming and numerical methods: A guide for engineers and scientists</em> (pp. 415–444). Academic Press.</p><p><a href="https://www.ams.org/journals/mcom/1965-19-090/S0025-5718-1965-0178586-1/"><strong>[3]</strong></a> Cooley, J. W., &amp; Tukey, J. W. (1965). An algorithm for the machine calculation of complex Fourier series. <em>Mathematics of computation</em>, 19(90), 297–301.</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html#scipy.fft.fft"><strong>[4]</strong></a> Scipy Documentation, API Reference, Discrete Fourier Transforms (scipy.fft.fft). [Accessed on 23/2/2023]</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fftfreq.html#scipy.fft.fftfreq"><strong>[5]</strong></a> Scipy Documentation, API Reference, Discrete Fourier Transforms (scipy.fft.fftfreq). [Accessed on 23/2/2023]</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.rfft.html#scipy.fft.rfft"><strong>[6]</strong></a> Scipy Documentation, API Reference, Discrete Fourier Transforms (scipy.fft.rfft). [Accessed on 23/2/2023]</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.rfftfreq.html#scipy.fft.rfftfreq"><strong>[7]</strong></a> Scipy Documentation, API Reference, Discrete Fourier Transforms (scipy.fft.rfftfreq). [Accessed on 23/2/2023]</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.electrocardiogram.html#scipy.misc.electrocardiogram"><strong>[8]</strong></a> Scipy Documentation, API Reference, Miscellaneous routines (scipy.misc.electrocardiogram). [Accessed on 23/2/2023]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acdd32f1b96a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fourier-transform-the-practical-python-implementation-acdd32f1b96a">Fourier Transform, the Practical Python Implementation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Discrete Fourier Transform (DFT)]]></title>
            <link>https://medium.com/data-science/learn-discrete-fourier-transform-dft-9f7a2df4bfe9?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7a2df4bfe9</guid>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[digital-signal-processing]]></category>
            <category><![CDATA[signal]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 13:38:42 GMT</pubDate>
            <atom:updated>2023-02-08T13:38:42.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mathematical and Coding Perspective</h4><p>Digital signal processing (DSP) is the computation of mathematical methods used to manipulate signal data <a href="https://doi.org/10.1016/B978-0-08-097768-3.00011-8"><strong>[1]</strong></a>. One of the most important tools in digital signal processing is the Discrete Fourier Transform (DFT). It is usually used to produce a signal’s frequency-domain (spectral) representation <a href="https://doi.org/10.1016/B978-0-08-099388-1.00003-0"><strong>[2]</strong></a>.</p><p>In this post, we will discuss how DFT works and how to implement it to output the spectrum of the signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8MmOdTZB8_nVotOX" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Discrete Fourier Transform (DFT)</h3><p>The Fourier Transform is the mathematical backbone of the DFT and the main idea behind Spectral Decomposition which concludes that a signal is nothing but a sum of sinusoids of different frequency components <a href="https://biblioteca.unisced.edu.mz/bitstream/123456789/1667/1/thinkdsp.pdf"><strong>[3]</strong></a>. Since all of the signal data we are working with are in digital form, a signal is a set of samples in the time domain. The Fourier transform on such discrete signals can be done using DFT, which can be used to switch back and forth between the time and the frequency domains. The time domain contains the samples of the signal, whereas the frequency domain represents the spectrum of the sinusoids that construct the signal <a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=da18cc0dc47a2e9f829bf752e86a985d0dcc22f3"><strong>[4]</strong></a>. The image below describes the relationship between time and frequency domains using DFT and IDFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*jH5HR0t0bZR8CbELgG6sMA.png" /><figcaption><strong>The relationship between time and frequency domains </strong><a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=da18cc0dc47a2e9f829bf752e86a985d0dcc22f3"><strong>[4]</strong></a><strong>. </strong>[Image by the Author]</figcaption></figure><p>Mathematically speaking, if we have a signal (xn) with N samples, the DFT of this signal is defined as <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*1v8YB_U9lpmg4FBUy2_R9Q.png" /><figcaption><strong>The DFT equation</strong> <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a></figcaption></figure><p><strong>Where:</strong></p><ul><li><strong><em>N</em></strong>: Number of samples</li><li><strong><em>n</em></strong>: Current sample</li><li><strong><em>k</em></strong>: Current frequency where <em>k </em>∈ [0, <em>N</em>−1]</li><li><strong><em>xn</em></strong>: The sine value at sample n</li><li><strong><em>Xk</em></strong>: The DFT which includes information on both amplitude and phase</li></ul><p>The output of the DFT (Xk) is an array of complex numbers that hold the information on the frequencies, amplitudes, and phases of sinusoids that construct the input signal. The first half of the DFT array (Xk) contains the positive frequency terms, while the second half contains the negative frequency terms. Also, when the input signal is only a real-valued signal, the first half is the conjugate of the second half of frequency terms and the spectrum is symmetric. So, we focus only on the first half (the positive frequency terms) in the case of real-valued signals <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>. The figure below represents each of the positive and the negative frequency terms in case the number of the input samples (N) is odd or even.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LHtGTqO7hAXIm8AFvi1F3Q.png" /><figcaption><strong>Positive and negative frequency terms </strong><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a><strong>. </strong>[Image by the Author]</figcaption></figure><p>The amplitude and the phase of each sinusoid that adds up to construct the signal can be calculated from the complex array (Xk) as follows (Im, and Re, are for Imagery and Real parts of a complex number, respectively) <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*_SEH2RioV5T2o-4TKpERvQ.png" /><figcaption><strong>The amplitude and the phase information can be calculated from these equations </strong><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a></figcaption></figure><h3>Let’s Code:</h3><p>We will build a function that calculates DFT based on the first equation above. But first, we should generate the signal that we want to use as an input for DFT. We will generate a signal that is a sum of 3 sine waves with frequencies (1,20,10)Hz and amplitudes (3,1,0.5). The sampling rate will be 200 samples per second. For generating the signal, I used a class, Signal, that you can use as well following <a href="https://gist.github.com/OmarAlkousa/4bd0bacb0ff976be4105777965854e06"><strong>this GitHub gist</strong></a>. You can easily generate any signal but I used this Signal class for more controllability.</p><h4><strong>Note</strong>:</h4><ul><li>The DFT and IDFT functions we will write below are released under the MIT license and all credits go to the authors of <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/Index.html"><strong>this book</strong></a>.</li><li>Both of the functions we will discuss are just to understand what is the mathematics behind DFT and what is the output of such transform. In practical use, there are faster and more efficient algorithms that can calculate the Fourier Transform, Fast Fourier Transform (FFT), and its inverse.</li></ul><p><strong>Let’s get started…</strong></p><pre># Import the required packages<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre># Generate the three signals using Signal class and its method sine()<br>signal_1hz = Signal(amplitude=3, frequency=1, sampling_rate=200, duration=2)<br>sine_1hz = signal_1hz.sine()<br>signal_20hz = Signal(amplitude=1, frequency=20, sampling_rate=200, duration=2)<br>sine_20hz = signal_20hz.sine()<br>signal_10hz = Signal(amplitude=0.5, frequency=10, sampling_rate=200, duration=2)<br>sine_10hz = signal_10hz.sine()<br><br># Sum the three signals to output the signal we want to analyze<br>signal = sine_1hz + sine_20hz + sine_10hz<br><br># Plot the signal<br>plt.plot(signal_1hz.time_axis, signal, &#39;b&#39;)<br>plt.xlabel(&#39;Time [sec]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.title(&#39;Sum of three signals&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*RvuroaYBTHAijwS-MwumwQ.png" /><figcaption><strong>The signal we generated using our class Signal.</strong> [Image by the Author]</figcaption></figure><p>Now we will build the DFT function to give us the sinusoids that construct the signal we generated above. Make sure to carefully read the comments on the code below as it helps you conduct the output of each line.</p><pre># Build a function that calculates the discrete Fourier transform<br>def DFT(signal):<br>  # Number of samples, 100 samples in our example<br>  N = len(signal)<br>  # The samples from 0 to N-1, [0, 1, 2, ..., 199] in our example<br>  n = np.arange(N)<br>  # Generate the frequencies, [[0], [1], [2], ..., [199]] in our example<br>  k = n.reshape((N,1))<br>  # e is a matrix of complex numbers with a shape of (N, N), (200, 200) in our example<br>  e = np.exp(-2j * np.pi * k * n / N)<br>  # dft is a matrix of complex numbers with a shape of (N,), (200,) in our example<br>  dft = np.dot(e,signal)<br>  return dft<br><br># Let&#39;s use the function<br>dft = DFT(signal= signal)<br><br># Calculate the amplitude spectrum of the signal<br>amp = np.abs(dft)<br><br># Generate the frequency axis<br>N = len(dft)<br>n = np.arange(N)<br>T = N/signal_1hz.sampling_rate<br>freq = n/T<br><br># Plot the spectrum<br>plt.figure(figsize = (8, 6))<br>plt.stem(freq, amp, &#39;b&#39;, markerfmt=&#39;o&#39;, basefmt=&#39;b&#39;)<br>plt.xlabel(&#39;Frequency [Hz]&#39;)<br>plt.ylabel(&#39;DFT Amplitude |X(freq)|&#39;)<br>plt.title(&#39;Spectrum of the signal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*mmCYDp9gUtEOYV-4jU5NDQ.png" /><figcaption><strong>The output of the DFT function is the spectrum of the signal.</strong> [Image by the Author]</figcaption></figure><p>The x-axis contains the frequency components that construct the signal. The y-axis represents the strength of each frequency component. The lowest frequency component in the spectrum is usually called the <strong>Fundamental Frequency</strong> and the frequency component with the largest amplitude is called the <strong>Dominant Frequency</strong> <a href="https://biblioteca.unisced.edu.mz/bitstream/123456789/1667/1/thinkdsp.pdf"><strong>[3]</strong></a>. In our example above, the 1Hz frequency component is the fundamental and the dominant frequency.</p><p>We can notice the symmetry of the spectrum at half of the sampling rate (try different rates); this is usually called the <strong>Folding Frequency</strong>. When recording a real-world signal (f(t)) with FN as the highest frequency component, the folding frequency should never go below FN to retrieve all of the signal’s information. And that’s according to <strong>Nyquist-Shannon Theorem</strong> <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>.</p><p>We can get the actual amplitude of the spectrum by normalizing it to the number of input samples (N). But when we focus only on the first half of the spectrum, in case the input is a real-valued signal, we normalize the spectrum by N/2 <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>. The code below is to normalize the first half of the spectrum [0, N/2] and to plot the spectrum.</p><pre># Get the length of one side of frequencies<br>n_oneside = N//2<br># Get the one side frequency<br>f_oneside = freq[:n_oneside]<br># Normalize the amplitude by N/2<br>one_side_dft = dft[:n_oneside]/n_oneside<br><br># Plot the first half<br>plt.stem(f_oneside, np.abs(one_side_dft))<br>plt.xlabel(&#39;Freq (Hz)&#39;)<br>plt.ylabel(&#39;DFT Amplitude |X(freq)|&#39;)<br>plt.title(&#39;The spectrum of the signal after normalization&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*xaTQyfqcOFeQpLJLl91dbw.png" /><figcaption><strong>The spectrum of the signal after the normalization.</strong> [Image by the Author]</figcaption></figure><h3>Inverse Discrete Fourier Transform (IDFT)</h3><p>Similarly, as you can go from the time domain to the frequency domain, you can get back from the frequency domain to the time domain using the Inverse Discrete Fourier Transform. This process is very useful in signal processing when you want to filter specific frequency components from the signal using DFT and then retrieve the signal back to its time domain using IDFT. The IDFT can be calculated from the Xk sequence following the equation <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*sxA81cFi9VrOsMCPhPg_dw.png" /><figcaption><strong>IDFT equation </strong><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a></figcaption></figure><p>Let’s build a function that can calculate the IDFT using the equation above.</p><pre>def IDFT(dft):<br>  # Number of frequencies, 200 components in our example<br>  N = len(dft)<br>  # The frequencies from 0 to N-1, [0, 1, 2, ..., 199] in our example<br>  k = np.arange(N)<br>  # Generate the samples, [[0], [1], [2], ..., [199]] in our example<br>  n = k.reshape((N,1))<br>  # If your input was a first half spectrum, 2j should be 1j to retrieve the signal<br>  e = np.exp(2j * np.pi * k * n / N)<br>  # dft is a matrix of complex numbers with a shape of (N,), (200,) in our example<br>  signal = np.dot(e,dft)/N<br>  return signal<br><br># Apply the Inverse Fourier Transform on the spectrum [dft]<br>sig = IDFT(dft)<br><br># Generate the time axis from sampling rate and length of dft<br>N = len(dft)<br>duration = N/signal_1hz.sampling_rate<br>time_axis = np.arange(0, 2, 1/200)<br><br># Plot the results of IDFT along with the original signal<br>plt.plot(time_axis, sig,&#39;b&#39;)<br>plt.plot(time_axis, signal, &#39;r&#39;)<br>plt.xlabel(&#39;Time [sec]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.title(&#39;Output of the IDFT&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*XcJmJCK1ttMirXXEmd8L8g.png" /><figcaption><strong>The signal retrieved by the IDFT function and the original signal are the same.</strong> [Image by the Author]</figcaption></figure><h3>The limit of DFT</h3><p>In the case of a signal with a big number of samples, the execution time of the DFT function will be long to apply the Fourier Transform on all of the data points of the signal. Fortunately, an efficient algorithm to calculate the DFT of the signal has been developed, the Fast Fourier Transform (FFT). This algorithm reduces the execution complexity from O(N²) to only O(NlogN), where N is the size of the data. The significant reduction of computation complexity by using FFT allows the wide use of Fourier Transform in engineering, science, and mathematics fields <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a>.</p><p>Python provides multiple functionalities that the user can use to apply Fourier Transform using Numpy or Scipy python packages. The code below represents the comparison of time execution using the DFT function we built above, the FFT using the Numpy package <a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fft.html"><strong>[6]</strong></a>, and the FFT Scipy package <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.fft.html"><strong>[7]</strong></a>. Using FFT from the Scipy package was the fastest.</p><pre># Import the scipy package<br>from scipy.fftpack import fft<br><br># Estimate the execution time of DFT using the function we&#39;ve built<br>print(&#39;Execution time of DFT Function:&#39;)<br>%timeit DFT(signal)<br># Estimate the execution time of DFT using FFT from numpy package<br>print(&#39;\nExecution time of FFT using Numpy pacakge:&#39;)<br>%timeit np.fft.fft(signal)<br># Estimate the execution time of DFT using FFT from scipy package<br>print(&#39;\nExecution time of FFT using Scipy package:&#39;)<br>%timeit scipy.fftpack.fft(signal)</pre><pre>Execution time of DFT Function:<br>17.3 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)<br><br>Execution time of FFT using Numpy pacakge:<br>8.72 µs ± 2.2 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)<br><br>Execution time of FFT using Scipy package:<br>8.27 µs ± 137 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)</pre><h3>Conclusion</h3><ul><li>We’ve learned how useful the Fourier Transform is in the signal processing field. And we’ve understood the main idea behind it.</li><li>We’ve pointed out the mathematical perspective of the Discrete Fourier Transform and how it can be calculated for a discrete signal.</li><li>We’ve built a function that calculates the DFT using the mathematical equation and we applied the function to a signal we generated using a class Signal we’ve built in this previous post.</li><li>We’ve learned that the output of the DFT is an array of complex numbers with N number of elements, the same as the number of samples of the input signal. These complex numbers hold information on the amplitude and the phase of the spectrum.</li><li>We’ve seen that the output of the DFT will be symmetrical to half of the sampling rate if the input signal is a real-value signal. And this is why we focus only on the positive frequency components.</li><li>An equation to calculate the Inverse Discrete Fourier Transform, IDFT, has been pointed out. And we’ve built a function to calculate the IDFT to retrieve the original signal from the spectrum.</li><li>We’ve discussed the limitation of the functions we’ve built and there is an efficient algorithm to calculate the Fourier transforms, Fast Fourier Transform.</li></ul><h3>References</h3><p><a href="https://doi.org/10.1016/B978-0-08-097768-3.00011-8"><strong>[1]</strong></a> R. Toulson, R., &amp; Wilmshurst, T. (2012). An Introduction to Digital Signal Processing. <em>Fast and Effective Embedded Systems Design</em> (pp. 219–242). Elsevier. <a href="https://doi.org/10.1016/B978-0-08-097768-3.00011-8">https://doi.org/10.1016/B978-0-08-097768-3.00011-8</a></p><p><a href="https://doi.org/10.1016/B978-0-08-099388-1.00003-0"><strong>[2]</strong></a> T. Giannakopoulos, T., &amp; Pikrakis, A. (2014). Signal Transforms and Filtering Essentials. <em>Introduction to Audio Analysis</em> (pp. 33–57). Elsevier. <a href="https://doi.org/10.1016/B978-0-08-099388-1.00003-0">https://doi.org/10.1016/B978-0-08-099388-1.00003-0</a></p><p><a href="https://biblioteca.unisced.edu.mz/bitstream/123456789/1667/1/thinkdsp.pdf"><strong>[3]</strong></a> Downey, A. (2016). Sounds and Signals. <em>Think DSP: Digital signal processing in Python</em> (pp. 1–11). (First edition). O’Reilly Media, Inc.</p><p><a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=da18cc0dc47a2e9f829bf752e86a985d0dcc22f3"><strong>[4]</strong></a> Thakur, B., &amp; Mehra, R. (2016). Discrete Fourier Transform Analysis with Different Window Techniques Algorithm. <em>International Journal of Computer Applications</em>, 975, 8887.</p><p><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html"><strong>[5]</strong></a> Kong, Q., Siauw, T., &amp; Bayen, A. (2020). Fourier Transform. <em>Python programming and numerical methods: A guide for engineers and scientists</em> (pp. 415–444). Academic Press.</p><p><a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fft.html"><strong>[6]</strong></a> Numpy Documentation, API Reference, Discrete Fourier Transform (numpy.fft). [Accessed on 2/2/2023]</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.fft.html"><strong>[7]</strong></a> Scipy Documentation, API Reference, Legacy discrete Fourier transform (scipy.fftpack). [Accessed on 2/2/2023]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7a2df4bfe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learn-discrete-fourier-transform-dft-9f7a2df4bfe9">Learn Discrete Fourier Transform (DFT)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Classes for Generating Signals]]></title>
            <link>https://medium.com/data-science/use-classes-for-generating-signals-6694d22e9a80?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6694d22e9a80</guid>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 14:05:50 GMT</pubDate>
            <atom:updated>2023-02-01T14:05:50.161Z</atom:updated>
            <content:encoded><![CDATA[<h4>Classes == More Code Readability</h4><p>During your work with signal data, you might end up programming multiple functions and methods that can implement the process you want to use on the signal data. However, at some point, it might be hard to keep tracking the quality of your methods applied to signals without prior knowledge of this data. Therefore, generating signal data with prior known parameters helps you better understand your program and method. Generating signals, especially sinusoidal signals, is very common in signal processing studies. And it is usually done for testing or to represent the use of different signal processing techniques, such as Discrete Fourier Transform, Wavelet analysis, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PtTFoiY4CvGhleHV" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we will learn how to use classes to build a signal generator that you can use to generate sinusoidal signals for further understanding signal processing methods.</p><p>Let’s start our coding journey with a simple code that generate a sinusoidal signal.</p><pre># Import the required package<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Generate the x-axis (from 0 to 1 with step of 1/200)<br>x = np.linspace(0,20,200)<br># Generate a sinusoidal 1D Array<br>y = np.sin(x)<br><br># Plot the result<br>plt.plot(x, y, &#39;b&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.title(&#39;Sinusoidal Signal&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ywigGLrhPpGI1_l6A7hdUw.png" /><figcaption>Generate a signal using Numpy package. [Image by the Author]</figcaption></figure><h3>Why classes?</h3><p>From the code above, it seems we can generate signals without using classes. So, why the classes are a good choice? <a href="https://docs.python.org/3/tutorial/classes.html">[1]</a></p><ul><li>The data is more controllable when using classes as you can build your object and methods that can be applied to control and get the signals without repeat coding like the above.</li><li>Using classes brings you more functionality. Classes allow you to define variables and functions as attributes.</li><li>More readability and flexibility of your code. With classes, your code becomes easier to be understood and used.</li><li>Classes play a major role in building packages. If you work a lot with signal data, you might consider building a special package that helps you with better and faster signal data analysis work.</li></ul><p><a href="https://github.com/AllenDowney/ThinkDSP.git"><strong>“Think DSP”</strong></a> is a great example of building a package specifically for Digital Signal Processing. <a href="https://medium.com/u/564e295fb7cf">Allen Downey</a> has his thoughts and experience in signal processing implemented into this package, from generating signals to analyzing spectrums and more.</p><h3>Classes, a Simple Start</h3><p>Defining a class is similar to defining functions. First, you need a proper name for your class. There are no such rules for naming a class but it’s preferred to be short and related to its functionality. Also, it’s common. Let’s define a class for our signal generator.</p><pre># Define a class<br>class Signal:<br>  # Statement 1<br>  # Statement 2</pre><p>Different objects can be defined inside the class. These objects can be variables or functions and can be passed as methods or attributes of the class. Variables in our signal generator class might be the frequency and amplitude of the signal. Let’s also define a function that prints these variables.</p><pre># Signal Generator Class<br>class Signal:<br>  &quot;&quot;&quot;<br>  Signal Generator<br>  &quot;&quot;&quot;<br>  # Define the frequency<br>  f = 10 # in Hz<br>  # Define the amplitude<br>  a = 2<br><br>  # Print the variables<br>  def vars(self):<br>    print(&#39;frequency=&#39;, self.f)<br>    print(&#39;amplitude=&#39;, self.a)</pre><p>In the code above, <strong>“self”</strong> represents the instance of the class and it’s used to access the attributes of the class and to bind the attributes with the given arguments <a href="https://www.geeksforgeeks.org/self-in-python-class/">[2]</a>. You can use any word other than “self” as the name has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers <a href="https://docs.python.org/3/tutorial/classes.html">[1]</a>. One last thing about the code above is the statement directly after defining the class. This is the documentation that describes the functionality of the class. It’s important to be implemented in your class as it makes your code more readable. The user of the class can access the documentation using the help function in python.</p><p>The code below represents how to access the variables or the functions of a class.</p><pre># Define a signal object<br>signal = Signal()<br># Print the frequency of the signal<br>print(signal.f)<br># Calling vars to print the Signal class variables<br>signal.vars()</pre><pre>10<br>frequency= 10<br>amplitude= 2</pre><h3>A Special Method for Classes</h3><p>Until now, not much flexibility has been presented by the classes above. But, fortunately, Python provides special methods that can be used to make the class more controllable. The most important method that we will discuss is the <strong>__init__()</strong> method. It is used to instantiate the class and its parameters customized to a specific initial state.</p><p>With that in mind, calling a class object will automatically invoke the init method and instantiate all the variables and functions implemented into the init method <a href="https://docs.python.org/3/tutorial/classes.html">[1]</a>. The code below is a modification done on the previous code by defining the init method.</p><pre># Signal Generator class<br>class Signal:<br>  &quot;&quot;&quot;<br>  Signal Generator<br>  &quot;&quot;&quot;<br><br>  # Initialize the class object<br>  def __init__(self, f, a):<br>    self.frequency = f<br>    self.amplitude = a<br>  <br>  # Print the varibles<br>  def vars(self):<br>    print(&#39;frequency=&#39;, self.frequency)<br>    print(&#39;amplitude=&#39;, self.amplitude)</pre><p>Now if we try to define a Signal object, we need to pass the frequency and the amplitude of the signal.</p><pre># Define a signal object<br>signal = Signal(f=10, a=2)<br># Print the frequency of the signal<br>print(signal.frequency)<br># Calling vars to print the Signal class variables<br>signal.vars()</pre><pre>10<br>frequency= 10<br>amplitude= 2</pre><p>Now that we understand how to define classes and their objects along with the special initializing method. It’s time to build the signal generator class that we want from the beginning. First, we need to point out the parameters we will implement in the init() method. The general form of a sinusoidal wave can be given following the equation <a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.01-The-Basics-of-waves.html">[3]</a>:</p><blockquote><em>y</em>(<em>t</em>)=<em>A</em>.<em>sin</em>(2<em>πf</em>+<em>ϕ</em>)</blockquote><p>Where:</p><ul><li><strong><em>A</em>:</strong> The amplitude of the signal</li><li><strong><em>f </em>:</strong> The frequency of the signal [Hz]</li><li><strong><em>ϕ</em>:</strong> The phase of the signal</li></ul><p>Two additional parameters should be added to our variables:</p><ul><li>The <strong>duration</strong> of the signal, in seconds</li><li>The <strong>sampling rate</strong>, samples per second</li></ul><pre># Building a class Signal for better use.<br>class Signal:<br>  &quot;&quot;&quot;<br>  Generate sinusoidal signals with specific ampltiudes, frequencies, duration,<br>  sampling rate, and phase.<br><br>  Example:<br>    signal = Signal(amplitude=10, sampling_rate=2000.0)<br>    sine = signal.sine()<br>    cosine = signal.cosine()<br>  &quot;&quot;&quot;<br><br>  def __init__(self, amplitude=1, frequency=10, duration=1, sampling_rate=100.0, phase=0):<br>    &quot;&quot;&quot;<br>    Initialize the Signal class.<br><br>    Args:<br>        amplitude (float): The amplitude of the signal<br>        frequency (int): The frequency of the signal Hz<br>        duration (float): The duration of the signal in second<br>        sampling_rate (float): The sampling per second of the signal<br>        phase (float): The phase of the signal in radians<br>    <br>    Additional parameters,which are required to generate the signal, are<br>    calculated and defined to be initialized here too:<br>        time_step (float): 1.0/sampling_rate<br>        time_axis (np.array): Generate the time axis from the duration and<br>                              the time_step of the signal. The time axis is<br>                              for better representation of the signal.<br>    &quot;&quot;&quot;<br>    self.amplitude = amplitude<br>    self.frequency = frequency<br>    self.duration = duration<br>    self.sampling_rate = sampling_rate<br>    self.phase = phase<br>    self.time_step = 1.0/self.sampling_rate<br>    self.time_axis = np.arange(0, self.duration, self.time_step)<br>  <br>  # Generate sine wave<br>  def sine(self):<br>    &quot;&quot;&quot;<br>    Method of Signal<br><br>    Returns:<br>        np.array of sine wave using the pre-defined variables (amplitude,<br>        frequency, time_axis, and phase)<br>    &quot;&quot;&quot;<br>    return self.amplitude*np.sin(2*np.pi*self.frequency*self.time_axis+self.phase)<br>  <br>  # Generate cosine wave<br>  def cosine(self):<br>    &quot;&quot;&quot;<br>    Method of Signal<br><br>    Returns:<br>        np.array of cosine wave using the pre-defined variables (amplitude,<br>        frequency, time_axis, and phase)<br>    &quot;&quot;&quot;<br>    return self.amplitude*np.cos(2*np.pi*self.frequency*self.time_axis+self.phase)</pre><h3>Let’s Use our Signal Class</h3><p>Suppose we want to generate a signal that is the sum of three sinusoidal signals. The frequencies of these three signals are (20, 2, 7)Hz, respectively. The amplitudes of these three signals are (2, 6, 1), respectively. The sampling rate of the signals is 1000. And lastly, the duration of the signals is 3 seconds. Let’s leave the phase of the signals as it is, 0.</p><pre># Define the first signal, 20Hz and amplitude of 2<br>s1 = Signal(amplitude=2, frequency=20, sampling_rate=1000.0, duration=3)<br>sine1 = s1.sine()<br><br># Define the second signal, 2Hz and amplitude of 6<br>s2 = Signal(amplitude=6, frequency=2, sampling_rate=1000.0, duration=3)<br>sine2 = s2.sine()<br><br># Define the second signal, 7Hz and amplitude of 1<br>s3 = Signal(amplitude=1, frequency=7, sampling_rate=1000.0, duration=3)<br>sine3 = s2.sine()<br><br># Our signal is the sum of the three signals<br>signal = sine1 + sine2 + sine3<br><br># Plot the signal<br>plt.plot(s1.time_axis, signal, &#39;r&#39;)<br>plt.xlabel(&#39;Time [sec]&#39;)<br>plt.ylabel(&#39;Amplitude&#39;)<br>plt.title(&#39;This signal is generated using Signal class&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*R81kQM3zJn1XVLEv4HguTQ.png" /><figcaption>Example generating signal using our Signal class. [Image by the Author]</figcaption></figure><h3>Conclusion</h3><ul><li>We’ve pointed out some of the useful properties of the code when using classes, e.g., more control of the data, more functionality of the code, and more readability and flexibility of your code.</li><li>We’ve learned how to build a class in python step-by-step. We started by defining the class and how to define a variable or a function as an object and pass it with the class as methods or attributes.</li><li>We’ve learned about the special method __init__() and how it is used to instantiate the class and its parameters customized to a specific initial state, which gives the user more control of the data.</li><li>We’ve built our final class as a signal generator that you can use to get sinusoidal signals with a specific frequency, sampling rate, amplitude, and duration.</li></ul><h3>References</h3><p><a href="https://docs.python.org/3/tutorial/classes.html">[1]</a> Python Documentation, Classes, A First Look at Classes. [Accessed at 28/1/2023]</p><p><a href="https://www.geeksforgeeks.org/self-in-python-class/">[2]</a> GeeksforGeeks, Classes, Self in Classes. [Accessed at 28/1/2023]</p><p><a href="https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.01-The-Basics-of-waves.html">[3]</a> Kong, Q., Siauw, T., &amp; Bayen, A. (2020). Python programming and numerical methods: A guide for engineers and scientists, Fourier Transform, The Basics of waves. Academic Press.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6694d22e9a80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/use-classes-for-generating-signals-6694d22e9a80">Use Classes for Generating Signals</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From DICOM Header to CSV file]]></title>
            <link>https://medium.com/data-science/from-dicom-header-to-csv-file-e2e442505651?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e442505651</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[health-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthcare-data]]></category>
            <category><![CDATA[dicom]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 04:21:02 GMT</pubDate>
            <atom:updated>2023-01-17T04:21:02.429Z</atom:updated>
            <content:encoded><![CDATA[<h3>From DICOM Header to CSV File</h3><h4>DICOM Metadata → CSV Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*g_pGK44-_JMjvqY14-4B3Q.png" /><figcaption>Convert DICOM Metadata into CSV files. [Image by the Author]</figcaption></figure><p>DICOM, Digital Imaging and Communications in Medicine, is the native format of medical images. DICOM files consider data beyond pixel data and store it as a DICOM header. Such data are the Patient’s age and weight, Modality, Image Dimension, and so on. In this post, we will use the PyDicom package to build a Python function that can extract specific metadata to use in further data analysis work.</p><h3>Background</h3><p>As mentioned above, DICOM files have metadata. This data is useful for any DICOM user, from the patient to the doctors and the modalities of the imaging systems. Furthermore, it’s treasury data that Data Scientists /Analysts can use to do very helpful insights.</p><p>A good thing about this metadata is that it’s represented in a standardized method where each DICOM attribute has a unique tag and keyword to give the user the information in a specific value representation.</p><p>Let’s get to code and see an example of DICOM headers…</p><h3>Let’s begin coding</h3><p>We will start with a simple example of reading a DICOM file to see the metadata representation. Then we’ll build a function to extract the data.</p><p>There are a lot of DICOM samples on the internet. And you can use your own DICOM files. For this post, I chose a <a href="https://www.kaggle.com/datasets/dmisky/dlwptvolumetricdicomlung">dataset</a> of 99 slices of chest-CT scans for one patient. You can find it on Kaggle (Credit for <a href="https://www.kaggle.com/dmisky">Kosarevsky Dmitry</a>. License: “Database: Open Database, Contents: Database Contents”, DbCL v1.0). I saved the dataset on my <a href="https://drive.google.com/drive/folders/1dbJpXVUBn0mSUxgJIqKZj4d_0thSeTW3?usp=sharing">Drive</a> so I can easily have access through GoogleColab.</p><h4>Reading DICOM using PyDicom</h4><p>In this example, we read the first slice and present only a part of the DICOM attributes because the whole output is so long. You can refer to this <a href="https://gist.github.com/OmarAlkousa/53b35934cd3fac3d381f0448b8e27073">GitHub Gist</a> to see the complete output.</p><pre># Install and import the package<br>!pip install pydicom<br>import pydicom<br><br># Reading a DICOM file from a specific path<br>dcm_data = pydicom.dcmread(&#39;/content/drive/MyDrive/Datasets/Kaggle/DICOM/dicom_lung/000000.dcm&#39;)<br>dcm_data</pre><pre>Dataset.file_meta -------------------------------<br>(0002, 0000) File Meta Information Group Length  UL: 196<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.3.6.1.4.1.14519.5.2.1.7085.2626.214140401149739061368142942055<br>(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian<br>(0002, 0012) Implementation Class UID            UI: 1.2.40.0.13.1.1.1<br>(0002, 0013) Implementation Version Name         SH: &#39;dcm4che-1.4.35&#39;<br>-------------------------------------------------<br>(0008, 0005) Specific Character Set              CS: &#39;ISO_IR 100&#39;<br>(0008, 0008) Image Type                          CS: [&#39;ORIGINAL&#39;, &#39;PRIMARY&#39;, &#39;AXIAL&#39;, &#39;CT_SOM5 SPI&#39;]<br>(0008, 0016) SOP Class UID                       UI: CT Image Storage<br>(0008, 0018) SOP Instance UID                    UI: 1.3.6.1.4.1.14519.5.2.1.7085.2626.214140401149739061368142942055<br>(0008, 0020) Study Date                          DA: &#39;20100227&#39;<br>(0008, 0021) Series Date                         DA: &#39;20100227&#39;<br>(0008, 0022) Acquisition Date                    DA: &#39;20100227&#39;<br>(0008, 0023) Content Date                        DA: &#39;20100227&#39;<br>(0008, 0030) Study Time                          TM: &#39;161937.171&#39;<br>(0008, 0031) Series Time                         TM: &#39;162536.14&#39;<br>(0008, 0032) Acquisition Time                    TM: &#39;162203.028699&#39;<br>...</pre><p>PyDicom wraps a DataSet class and for each DICOM attribute, it starts with the tag as a key of the DataSet and the data element as a value. The image below describes the contents of the DataSet and DataElement classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*k6A9sw3-EQQOq9J9.png" /><figcaption>The contents of PyDicom DataSet class. [Image by the Author]</figcaption></figure><p>PyDicom package provides many methods and attributes to use with DataSet and DataElement classes. We won’t dive into details about it. If you want to learn about it, refer to this previous post.</p><p><a href="https://towardsdatascience.com/introducing-pydicom-its-classes-methods-and-attributes-518c1d71162">Introducing PyDicom, its Classes, Methods, and Attributes.</a></p><h3>Extract the metadata</h3><p>The main idea we will depend on is that we can iterate over the DICOM files in a specific folder. Then we will iterate over the whole attributes in each file and extract only the attributes specified in advance. We will use the keywords of DICOM attributes as it’s the best choice because:</p><ul><li>Each DICOM attribute has its unique keyword.</li><li>The keywords are better than tags as they are human-readable.</li></ul><p>There are dozens of attributes that can characterize DICOM files. So, you cannot just read all of them. You need to focus only on the attributes that you might counter during your work. For this purpose, I highly recommend this great <a href="https://dicom.innolitics.com/ciods">DICOM Standard Browser</a> which was built by <a href="https://innolitics.com/">Innolitics</a>, you just need to search for the attribute you want to learn about. Make sure you type the keywords you want correctly.</p><p><strong>Now that we understand what we will do, let’s extract some DICOM metadata:)</strong></p><p>We will need <strong>glob </strong>package to manipulate the paths of DICOM files. Also, the <strong>Pandas </strong>package is required to write the CSV file from a pandas data frame. The glob module finds all the path names matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.</p><p>All that’s left to set our python environment ready is to import the packages and build our function. Documentation of the function will be added to explain the parameters and the output of the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d01f27954457e5feeab71b5a0430d91/href">https://medium.com/media/5d01f27954457e5feeab71b5a0430d91/href</a></iframe><p>Let’s try the above function. First, we decide what DICOM attributes we are interested in. For example, I want to calculate the DLP index from a series of Chest CT scans. <strong>DLP index, Dose-Length Product</strong>, is a commonly used index that factors in the length of the scan to show overall dose output. It’s commonly used and represented at the consoles of modern modalities because it gives a rough estimation of the effective dose (ED) in advance.</p><p>DLP can be calculated from CTDIvol, another CT index that describes the average dose for a single image for the selected CT conditions of operation represented in mGy. Dose–length product (DLP) is used to calculate the dose for a series of scans or a complete examination and is defined by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*2Pdw8YoJxqGjkuTwgIrj_w.png" /></figure><p>Where i is for the ith CTDIvol for each image that covers a length of Li. For Li, we will use the reconstruction interval between every two sequenced images because it is what actually determines the number of images that correspond to a given scan length. <strong>Slice Location</strong> will help us calculate the reconstruction intervals in millimeters.</p><p>So, the metadata we need to calculate DLP are <strong>CTDIvol </strong>represented in mGy (milli-Gray) and the <strong>SliceLocation </strong>of each axial slice expresses in mm. Let’s use the function we’ve built above to extract them.</p><pre># Extract the SliceLocation and CTDIvol from DICOM files of Chest-CT<br>df = dicom2csv(extract = [&#39;SliceLocation&#39;, &#39;CTDIvol&#39;],<br>          folder_path = &#39;/content/drive/MyDrive/Datasets/Kaggle/DICOM/dicom_lung&#39;,<br>          csv_file_name = &#39;data.csv&#39;, <br>          return_dataframe = True)</pre><p><strong>Note</strong> that reading DICOM files is done arbitrarily. So, we need to sort the data based on the slice location.</p><pre># Sort the data frame to get the slices in order<br>df.sort_values(by=&#39;SliceLocation&#39;, inplace=True, ignore_index=True)<br>df</pre><pre>    SliceLocation  CTDIvol<br>0          -288.0    8.550<br>1          -285.0    8.450<br>2          -282.0    8.250<br>3          -279.0    8.025<br>4          -276.0    7.850<br>..            ...      ...<br>94           -6.0   12.450<br>95           -3.0   12.325<br>96            0.0   12.125<br>97            3.0   11.925<br>98            6.0   11.575<br><br>[99 rows x 2 columns]</pre><p>Vividly, the reconstruction interval is 3.0 mm from the look at the “SliceLocation” column, which is the same as the slice thickness. You can try the following line code to ensure that the reconstruction interval is the same for all slices.</p><pre># Calculate the reconstruction interval from SliceLocation<br>[df[&#39;SliceLocation&#39;][i+1] - df[&#39;SliceLocation&#39;][i] for i in range(0,len(df)-1)]</pre><p>Back to the DLP equation, Li is the same for all slices and it’s 0.3 cm. Our final touch is to multiply each CTDIvol by 0.3 and sum the variables.</p><pre>import numpy as np<br># Calculating DPL = sum(CTDIvol * 0.3)<br>print(&#39;DLP = &#39;,np.sum(df[&#39;CTDIvol&#39;].values * 0.3), &#39;mGy*cm&#39;)</pre><pre>DLP =  239.90999999999994 mGy*cm</pre><p>It is important to remember that the CTDIvol or its derivative the DLP, as seen on consoles and outputted on the DICOM images, does not represent the actual absorbed or effective dose for the patient. They should be taken as an index of radiation output by the system for comparison purposes. And the calculation of Effective Dose based on DLP is just a rough estimation.</p><p>DLP calculation was just one single example of how useful extracting data from DICOM headers is. And the python function we’ve built makes it easy to deal with the specified metadata.</p><h3>Conclusion</h3><ul><li>We’ve seen how to use the PyDicom package to read DICOM files. And the power of using DICOM metadata in our analyzing work.</li><li>We’ve built a function that converts the specific data from DICOM headers into a CSV file to use in further insights.</li><li>We’ve used the function to calculate the Dose Length Product, which is a common used parameter in dose estimation for CT modalities.</li></ul><p><strong><em>Thanks For Reading…</em></strong></p><h3>Recommendation</h3><ul><li><strong><em>DICOM Metadata — A Useful Resource for Big Data Analytics:</em></strong><br>This <a href="https://healthmanagement.org/c/healthmanagement/issuearticle/dicom-metadata-a-useful-resource-for-big-data-analytics">article</a> provides an overview of new ways to represent data by combining patient access and DICOM information, advanced use of medical imaging metadata, analysis of radiation dose and image segmentation, and deep learning for feature engineering to enrich data.</li><li>For more details about DICOM: refer to the previous blog, <a href="https://medium.com/@omar.ok1998/what-is-dicom-a28c5fe24c9d"><strong><em>What is DICOM?</em></strong></a></li><li><strong>Caculating DLP</strong> from Computed Tomography Dose Index, CTDIvol.</li></ul><p><a href="https://howradiologyworks.com/dlp-calculator/">Simple Calculator For Effective Dose In CT (DLP -&gt; Eff Dose): Radiologic Technologist&#39;s Guide To Effective Dose (mSv) In CT From Dose Length Product (mGy Cm) * How Radiology Works</a></p><h3>References</h3><p>[1] Dataset of 99 CT slices, <a href="https://www.kaggle.com/datasets/dmisky/dlwptvolumetricdicomlung">dlwpt-volumetric-dicom-lung</a>, Kaggle, <a href="https://www.kaggle.com/dmisky">Kosarevsky Dmitry</a>, License: “Database: Open Database, Contents: Database Contents”, DbCL v1.0.</p><p>[2] PyDicom Documentation, <a href="https://pydicom.github.io/pydicom/stable/old/pydicom_user_guide.html"><strong>User Guide</strong></a>, [Accessed at 25/12/2022]</p><p>[3] PyDicom Documentation, <a href="https://pydicom.github.io/pydicom/stable/guides/element_value_types.html"><strong>Element VRs and Python types</strong></a>, [Accessed at 25/12/2022]</p><p>[4] PyDicom Documentation,<strong> </strong><a href="https://pydicom.github.io/pydicom/stable/reference/index.html"><strong>API Reference</strong></a>, [Accessed at 25/12/2022]</p><p>[5] Innolitics, DICOM Standard Browser, (2022), <a href="https://dicom.innolitics.com/ciods/ct-image/ct-image/00189345"><strong>CTDIvol Attribute</strong></a>, [Accessed at 10/1/2023]</p><p>[6] I. A. Tsalafoutas and S. I. Metallidis, “A method for calculating the dose length product from CT DICOM images,” <em>BJR</em>, vol. 84, no. 999, pp. 236–243, Mar. 2011, doi: <a href="https://doi.org/10.1259/bjr/37630380">10.1259/bjr/37630380</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e442505651" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-dicom-header-to-csv-file-e2e442505651">From DICOM Header to CSV file</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing PyDicom, its Classes, Methods, and Attributes.]]></title>
            <link>https://medium.com/data-science/introducing-pydicom-its-classes-methods-and-attributes-518c1d71162?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/518c1d71162</guid>
            <category><![CDATA[healthcare-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dicom]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 13:50:26 GMT</pubDate>
            <atom:updated>2023-01-04T13:50:26.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing PyDicom, Its Classes, Methods, and Attributes</h3><h4>PyDicom…Beyond Pixel Data</h4><p>If you are a Pythonista and you’re working with Medical Data, especially DICOM data, you’ve probably heard of the great python package PyDicom. In this post, you’ll learn the basics of this package. We’ll discuss PyDicom classes (DataSet, DataElement, Sequence) and some useful methods and attributes that you can apply to PyDicom classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sAAJm3Vj0QbeUB8a" /><figcaption>Photo by <a href="https://unsplash.com/@owenbeard?utm_source=medium&amp;utm_medium=referral">Owen Beard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>PyDicom is a pure Python package for working with DICOM files such as medical images, reports, and radiotherapy objects. PyDicom makes it easy to read and write these complex files into natural pythonic structures for easy manipulation.</p><blockquote>DICOM, Digital Imaging and Communications in Medicine, is the standard language of Medical Imaging Systems. When you hear the word “DICOM”, you probably think of it as just medical images. But <strong>Healthcare Data Scientists/Analysts</strong> may consider it as treasury as any other <strong>medical Dataset</strong>. Because it goes beyond just data of pixels. A DICOM file contains many useful data related to the patient, the imaging modality, and others.</blockquote><p>Dealing with DICOM metadata and accessing specific attributes is beneficial for anyone, including data scientists/analysts, working with DICOM files. Luckily, PyDicom provides many useful functions, methods, and attributes on DICOM files.</p><blockquote>Thanks to the creators and contributors of PyDicom</blockquote><h3>Let’s Begin Coding</h3><p>When I want to discover a new Python package, I usually begin with general examples using this package and then dive into it more and more gradually. My main purpose is to learn how to extract the metadata of many DICOM files and convert it to a Dataset that I can use for analysis and exploration.</p><p>So… let’s begin our journey with a common example of PyDicom.</p><h4><strong>We will discuss the following:</strong></h4><blockquote><strong><em>Example of reading a DICOM File</em></strong></blockquote><blockquote><strong><em>Core Elements in PyDicom</em></strong></blockquote><blockquote><strong><em>PyDICOM DataSet</em></strong></blockquote><blockquote><strong><em>Methods for PyDicom DataSet<br></em> .keys()</strong> Method<br><strong> .values()</strong> Method<br> <strong>.elements()</strong> Method<br><strong>.group_dataset()</strong> Method<br><strong>.dir() Method</strong></blockquote><blockquote><strong><em>Attributes for PyDicom DataSet<br> </em>pixel_array</strong> Attribute</blockquote><blockquote><strong><em>PyDicom DataElement</em></strong></blockquote><blockquote><strong><em>PyDicom Sequence</em></strong></blockquote><blockquote><strong><em>PyDicom vs. ImageIO</em></strong></blockquote><h4>Example of reading a DICOM File</h4><p>To read a DICOM file using pydicom, you can use the following steps:</p><ul><li>Install pydicom: To use pydicom, you will need to install it using pip.</li></ul><pre># Install PyDicom Package<br>!pip install pydicom</pre><pre>Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/<br>Collecting pydicom<br>  Downloading pydicom-2.3.1-py3-none-any.whl (2.0 MB)<br>     |████████████████████████████████| 2.0 MB 5.4 MB/s <br>Installing collected packages: pydicom<br>Successfully installed pydicom-2.3.1</pre><ul><li>Import the pydicom library: In your Python script, you will need to import the pydicom library in order to use it.</li></ul><pre># Import the pacakage<br>import pydicom</pre><p>There are a lot of DICOM samples on the internet. And you can use your own DICOM files. For this post, I chose a <a href="https://www.kaggle.com/datasets/dmisky/dlwptvolumetricdicomlung">dataset</a> of 99 slices of chest-CT scans for one patient. You can find it on Kaggle. I saved the dataset on my <a href="https://drive.google.com/drive/folders/1dbJpXVUBn0mSUxgJIqKZj4d_0thSeTW3?usp=sharing">Drive</a> so I can easily have access through GoogleColab.</p><blockquote><strong>Note:</strong> Sometimes, the output of some code lines will be too long and bulky. Sorry in advance about that!!! But this a great chance for you to get a taste of how DICOM files look like in real life.</blockquote><ul><li>Read the DICOM file: To read a DICOM file, you can use the <strong>dcmread</strong> function, which returns a Dataset object containing the data from the DICOM file.</li></ul><pre># Reading a DICOM file from a specific path<br>dcm_data = pydicom.dcmread(&#39;/content/drive/MyDrive/Datasets/Kaggle/DICOM/dicom_lung/000000.dcm&#39;)<br>dcm_data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ZBqnqop5RJ1XjOV-pBZkHA.png" /><figcaption>The full output is added as a GitHub gist following this <a href="https://gist.github.com/OmarAlkousa/53b35934cd3fac3d381f0448b8e27073">link</a>. [Image by the Author]</figcaption></figure><p>Clearly, there are a lot of DICOM metadata other than pixel data. But we can see a pattern of the output, whereas the DICOM attributes are written row by row. Each row has a unique tag and other core elements of the DICOM attribute. Let’s discuss them in more detail.</p><h3>Core Elements in PyDicom</h3><p>Applying <strong>.dcmread()</strong> wraps a DataSet, a dictionary data structure {}. This DataSet contains keys and values represented like the following:</p><ul><li><strong><em>Keys:</em></strong> contains the DICOM Tags of the attributes specified in the DICOM file you are reading. Examples of the keys like:<br> - (0x0010, 0x0010) PatientName attribute.<br> - (0x0028, 0x0010) Rows attribute.<br> - (0x7fe0, 0x0010) PixelData attribute.<br>The tags’ numbers consist of two <strong>hexadecimal</strong>, the first refers to the group, and the second refers to a specific element. So, you might find many attributes that have the same first number of tags.</li><li><strong><em>Values:</em></strong> the values of this dictionary generally contain the following:<br> - <strong>Tag:</strong> the element’s tag like (0028, 0030), for example.<br> - <strong>Keyword:</strong> describes what the attribute refers to. The keyword of the tag (0028, 0030) is “Pixel Spacing”.<br> - <strong>VR:</strong> it’s only two characters that refer to the Value Representation of the element, which describes the data type and format of the attribute value. The VR of the tag (0028, 0030) is “DS”, Decimal String. You can see the VR of any tag and how it is represented using Python structures following the<strong> </strong><a href="https://pydicom.github.io/pydicom/stable/guides/element_value_types.html"><strong>link</strong></a>.<br> - <strong>Value:</strong> the actual value of the element. It could be an integer, a string, a list, or even a <strong>Sequence</strong>, which is a dataset of attributes. The value of the tag (0028, 0030) is a list of two floats that represent the physical distance along the rows and columns, respectively, in mm. An example of this list is [0.564453125, 0.564453125].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*7eZSqrnZ3PhlYOzqTAWysg.png" /><figcaption>The output of dcmread() function. [Image by the Author]</figcaption></figure><p>Now that we understand reading a DICOM file using PyDicom requires working directly with the main class, which is DataSet. Let’s Discuss it in more depth and see what are the contents of a DataSet.</p><h3>PyDicom DataSet</h3><p>A DICOM DataSet is a mutable mapping of DICOM DataElements. Each DataElement, a value of the dictionary, in the DICOM DataSet has a unique tag, a key of the dictionary, that identifies it. For example, the “PatientName” attribute corresponds to the tag (0x0010, 0x0010) in the DICOM standard, which identifies the patient’s name data element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnZYT8T5us2nbtmvZGUjLQ.png" /><figcaption>The contents of PyDicom DataSet class. [Image by the Author]</figcaption></figure><p>You can access specific DICOM attributes in many different ways like the following:</p><pre># Extract the patient&#39;s name.<br>patient_name = dcm_data.PatientName<br>patient_name</pre><pre>&#39;C3N-00247&#39;</pre><p>Or you can access the same attribute, PatientName, using its unique tag. For example, the tag of the PatientName attribute is (0010, 0010). <strong><em>Note</em></strong><em> </em>that the numbers are in Hexadecimals as it is in the DICOM Standard.</p><pre># Extract the patient&#39;s name using its unique DICOM tag (0010, 0010)<br>dcm_data[0x0010, 0x0010]</pre><pre>(0010, 0010) Patient&#39;s Name                      PN: &#39;C3N-00247&#39;</pre><p>Notice that using the tag, which is the key of the dataset dictionary, yields the whole value of the dictionary and not only the actual value of the attribute. To get only the actual value, you should use the .value attribute.</p><pre># Extract the patient&#39;s name using its unique DICOM tag (0010, 0010)<br>dcm_data[0x0010, 0x0010].value</pre><pre>&#39;C3N-00247&#39;</pre><p>It’s up to you to decide whether you extract the specific attribute using its unique tag or using its keyword. Now let’s see some of the useful methods and attributes we can use with the DataSet class.</p><h3>Methods for PyDicom DataSet</h3><h4>.keys() Method</h4><p>Using <strong>.keys()</strong> returns the list of the keys of the DataSet dictionary. This method could be helpful when joining metadata from multiple sources of DICOM files that have common DICOM attributes.</p><pre># Extract the keys, the DICOM tags, that are in a DICOM file<br>dcm_data.keys()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECwvY7kWpWkpr0Ad38Ex9w.png" /><figcaption>The output of .keys() method. [Image by the Author]</figcaption></figure><h4>.values() Method</h4><p>This method returns a list of the values of the DataSet dictionary. It’s kinda bulky and not preferred to read in this form. But this method could be useful for iterating over a list of values in some cases.</p><pre># Extract the values, the DICOM attributes, that are in a DICOM file<br>dcm_data.values()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTslIxG32MAcxTEp-2zrqQ.png" /><figcaption>Part of the output of .values() method. [Image by the Author]</figcaption></figure><h4>.elements() Method</h4><p>Using .elements() yields the top-level elements of the Dataset. This method will be useful when you don’t need the DICOM attributes in any of the Sequences that you might find in the DICOM files you’re working with. Notice how the Sequences are represented when using the .elements() method in the output figure below.</p><pre># Extract the top-level elements of the Dataset Class<br>[*dcm_data.elements()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*SDnD--_8ArvxCbMskQM32Q.png" /><figcaption>The full output of the .elements() method is added as a GitHub gist following the <a href="https://gist.github.com/OmarAlkousa/03ce85834bdfbb0e65bda9a7989f5e3d">link</a>. [Image by the Author]</figcaption></figure><h4>.group_dataset() Method</h4><p>As we’ve mentioned above, you might find many attributes that have the same first number. These tags, the ones with a common first tag, usually describe a common parameter. For example, the attributes with the common first tag (0x0010) usually refer to Patient-related attributes. Attributes with the first tag (0x0028) describe <strong>Image Pixel</strong> attributes. Sometimes it’s helpful to see all the attributes that are related to a specific parameter. Using the method (.group_dataset) returns a Dataset containing only elements of a certain group.</p><pre># Extract the attributes related to 0x0028 tag, these are related to ImagePixel<br>dcm_data.group_dataset(0x0028)</pre><pre>(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.564453125, 0.564453125]<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, 0106) Smallest Image Pixel Value          US: 0<br>(0028, 0107) Largest Image Pixel Value           US: 4095<br>(0028, 0303) Longitudinal Temporal Information M CS: &#39;MODIFIED&#39;<br>(0028, 1050) Window Center                       DS: [-500, 40]<br>(0028, 1051) Window Width                        DS: [1500, 400]<br>(0028, 1052) Rescale Intercept                   DS: &#39;-1024.0&#39;<br>(0028, 1053) Rescale Slope                       DS: &#39;1.0&#39;<br>(0028, 1055) Window Center &amp; Width Explanation   LO: [&#39;WINDOW1&#39;, &#39;WINDOW2&#39;]</pre><h4>.dir() Method</h4><p>Return an alphabetical list of element keywords in the Dataset. This is a great choice to give the first insight into the metadata you’re dealing with.</p><pre># An alphabetical list of the element keywords in the DICOM DataSet.<br>dcm_data.dir()</pre><pre>[&#39;AccessionNumber&#39;, &#39;AcquisitionDate&#39;, &#39;AcquisitionNumber&#39;, &#39;AcquisitionTime&#39;,<br> &#39;BitsAllocated&#39;, &#39;BitsStored&#39;, &#39;BodyPartExamined&#39;, &#39;CTDIvol&#39;,<br> &#39;ClinicalTrialTimePointDescription&#39;, &#39;ClinicalTrialTimePointID&#39;, &#39;Columns&#39;,<br> &#39;ContentDate&#39;, &#39;ContentTime&#39;, &#39;ConvolutionKernel&#39;, &#39;DataCollectionDiameter&#39;,<br> &#39;DateOfLastCalibration&#39;, &#39;DeidentificationMethod&#39;, &#39;DeidentificationMethodCodeSequence&#39;,<br> &#39;DistanceSourceToDetector&#39;, &#39;DistanceSourceToPatient&#39;, &#39;EstimatedDoseSaving&#39;,<br> &#39;EthnicGroup&#39;, &#39;Exposure&#39;, &#39;ExposureModulationType&#39;, &#39;ExposureTime&#39;,<br> &#39;FilterType&#39;, &#39;FocalSpots&#39;, &#39;FrameOfReferenceUID&#39;, &#39;GantryDetectorTilt&#39;,<br> &#39;GeneratorPower&#39;, &#39;HighBit&#39;, &#39;ImageComments&#39;, &#39;ImageOrientationPatient&#39;,<br> &#39;ImagePositionPatient&#39;, &#39;ImageType&#39;, &#39;InstanceNumber&#39;, &#39;KVP&#39;, &#39;LargestImagePixelValue&#39;,<br> &#39;LongitudinalTemporalInformationModified&#39;, &#39;Manufacturer&#39;, &#39;ManufacturerModelName&#39;,<br> &#39;Modality&#39;, &#39;PatientAge&#39;, &#39;PatientBirthDate&#39;, &#39;PatientID&#39;, &#39;PatientIdentityRemoved&#39;,<br> &#39;PatientName&#39;, &#39;PatientPosition&#39;, &#39;PatientSex&#39;, &#39;PerformedProcedureStepStartDate&#39;,<br> &#39;PerformedProcedureStepStartTime&#39;, &#39;PhotometricInterpretation&#39;, &#39;PixelData&#39;,<br> &#39;PixelRepresentation&#39;, &#39;PixelSpacing&#39;, &#39;PositionReferenceIndicator&#39;, &#39;ProtocolName&#39;,<br> &#39;ReasonForStudy&#39;, &#39;ReconstructionDiameter&#39;, &#39;ReferencedImageSequence&#39;,<br> &#39;ReferencedStudySequence&#39;, &#39;ReferringPhysicianName&#39;, &#39;RequestedProcedureDescription&#39;,<br> &#39;RescaleIntercept&#39;, &#39;RescaleSlope&#39;, &#39;RotationDirection&#39;, &#39;Rows&#39;, &#39;SOPClassUID&#39;,<br> &#39;SOPInstanceUID&#39;, &#39;SamplesPerPixel&#39;, &#39;SeriesDate&#39;, &#39;SeriesDescription&#39;,<br> &#39;SeriesInstanceUID&#39;, &#39;SeriesNumber&#39;, &#39;SeriesTime&#39;, &#39;SingleCollimationWidth&#39;,<br> &#39;SliceLocation&#39;, &#39;SliceThickness&#39;, &#39;SmallestImagePixelValue&#39;, &#39;SoftwareVersions&#39;,<br> &#39;SourceImageSequence&#39;, &#39;SpecificCharacterSet&#39;, &#39;SpiralPitchFactor&#39;, &#39;StudyComments&#39;,<br> &#39;StudyDate&#39;, &#39;StudyDescription&#39;, &#39;StudyID&#39;, &#39;StudyInstanceUID&#39;, &#39;StudyPriorityID&#39;,<br> &#39;StudyStatusID&#39;, &#39;StudyTime&#39;, &#39;TableFeedPerRotation&#39;, &#39;TableHeight&#39;, &#39;TableSpeed&#39;,<br> &#39;TimeOfLastCalibration&#39;, &#39;TotalCollimationWidth&#39;, &#39;WindowCenter&#39;, &#39;WindowCenterWidthExplanation&#39;,<br> &#39;WindowWidth&#39;, &#39;XRayTubeCurrent&#39;]</pre><p>A filter of a specific set of attributes can be implemented as an argument to the .dir() method.</p><pre># Extract all the attributes that have &quot;Pixel&quot; in its keywords<br>dcm_data.dir(&#39;Pixel&#39;)</pre><pre>[&#39;LargestImagePixelValue&#39;,<br> &#39;PixelData&#39;,<br> &#39;PixelRepresentation&#39;,<br> &#39;PixelSpacing&#39;,<br> &#39;SamplesPerPixel&#39;,<br> &#39;SmallestImagePixelValue&#39;]</pre><h3>Attributes for PyDicom DataSet</h3><p>There are some attributes that you can use with the DataSet class. But I will point out only one, the most important and commonly used attribute, <strong>pixel_array</strong>.</p><pre># Extract the image pixels<br>dcm_data.pixel_array</pre><pre>array([[356, 244, 201, ..., 190, 224,  76],<br>       [309, 387, 370, ..., 122,  17,   6],<br>       [334, 476, 486, ...,  29,  46,  47],<br>       ...,<br>       [ 98, 188, 186, ..., 156,  86, 125],<br>       [ 66, 138, 139, ..., 221,  74,  81],<br>       [168, 173, 100, ..., 188, 135, 147]], dtype=uint16)</pre><pre># Image representation<br>im = dcm_data.pixel_array<br><br>plt.imshow(im, cmap=&#39;gray&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Axial Slice of a Chest-CT&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*SdzIqHlv0WlfUZ3fBno5zg.png" /><figcaption>[Image by the Author]</figcaption></figure><h3>PyDicom DataElement</h3><p>As we’ve mentioned above, a DataSet is a PyDicom class that contains a set of DICOM tags as keys and values as DICOM DataElements. DataElements are the values of the attributes or the metadata that you might find during reading DICOM files. It’s useful to be able to access specific information that might interest you in your work or research without searching about it in such pretty large text-like data like above. You can access specific info inside a specific DataElement using attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ImH8HOggI5ZQPjGNq8QFNg.png" /><figcaption>The contents of a PyDicom DataElement class and the way to access specific info. [Image by the Author]</figcaption></figure><pre># Return the element&#39;s keyword (if known) as str<br>kwrds = dcm_data[0x0010, 0x0010].keyword<br><br># Return the DICOM dictionary name for the element as str<br>name = dcm_data[0x0010, 0x0010].name<br><br># Return the element&#39;s Value Representation<br>vr = dcm_data[0x0010, 0x0010].VR<br><br># Return the element&#39;s value.<br>value = dcm_data[0x0010, 0x0010].value<br><br>print(&quot;The element&#39;s Keyword              : &quot;, kwrds)<br>print(&quot;The element&#39;s name                 : &quot;, name)<br>print(&quot;The element&#39;s Value Representation : &quot;, vr)<br>print(&quot;The element&#39;s value                : &quot;, value)</pre><pre>The element&#39;s Keyword              :  PatientName<br>The element&#39;s name                 :  Patient&#39;s Name<br>The element&#39;s Value Representation :  PN<br>The element&#39;s value                :  C3N-00247</pre><h3>PyDicom Sequence</h3><p>The DataElement inside a PyDicom DataSet could contain values that are strings, integers, lists, or even a Sequence of data. The sequence is derived from Python’s list. But it can even be a DataSet. Let’s see how to access specific parameters within a particular Sequence. Since there’s bulky information in the file we’re working with, let’s use the method .dir(*filter). With a proper filter implemented as an argument, we can extract the names of the “Sequence”s.</p><pre># Extract all the attributes that have &quot;Sequence&quot; in its keywords<br>dcm_data.dir(&#39;Sequence&#39;)</pre><pre>[&#39;DeidentificationMethodCodeSequence&#39;,<br> &#39;ReferencedImageSequence&#39;,<br> &#39;ReferencedStudySequence&#39;,<br> &#39;SourceImageSequence&#39;]</pre><p>Let’s try to work with De-identification Method Code Sequence.</p><pre># Return a specific Sequence, &quot;DeidentificationMethodCodeSequence&quot;<br>dcm_data.DeidentificationMethodCodeSequence</pre><pre>&lt;Sequence, length 8&gt;</pre><p>To print out all the elements in the Sequence, we can use the indices.</p><pre># Extract the contents of a Sequence<br>dcm_data.DeidentificationMethodCodeSequence[:]</pre><pre>[(0008, 0100) Code Value                          SH: &#39;113100&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Basic Application Confidentiality Profile&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113101&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Clean Pixel Data Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113104&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Clean Structured Content Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113105&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Clean Descriptors Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113107&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Retain Longitudinal Temporal Information Modified Dates Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113108&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Retain Patient Characteristics Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113109&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Retain Device Identity Option&#39;,<br> (0008, 0100) Code Value                          SH: &#39;113111&#39;<br> (0008, 0102) Coding Scheme Designator            SH: &#39;DCM&#39;<br> (0008, 0104) Code Meaning                        LO: &#39;Retain Safe Private Option&#39;]</pre><p>To access specific info inside the Sequence, we can use its index.</p><pre># Return the info of specific line in a Sequence<br>dcm_data.DeidentificationMethodCodeSequence[0].CodeMeaning</pre><pre>&#39;Basic Application Confidentiality Profile&#39;</pre><h3><strong><em>PyDicom vs. ImageIO</em></strong></h3><p>Personal opinion, I found PyDicom the best package to deal with DICOM files. It’s kinda obvious because it’s specifically designed for DICOM. It provides more flexible options for the programmer, especially when the user wants to deal with DICOM metadata and not just pixel data. But on the other side, if I want only the pixel data, I would prefer using ImageIO as it provides only the basic metadata that I need to deal with pixel data. To see more about using ImageIO with DICOM files, check this post.</p><p><a href="https://towardsdatascience.com/dealing-with-dicom-using-imageio-python-package-117f1212ab82">Dealing with DICOM Using ImageIO Python Package</a></p><h3>Conclusion:</h3><ul><li>PyDicom DataSet is the main class of the package. And the user will directly deal with it.</li><li>A DataSet is a Python dictionary structure that contains DICOM tags as keys and DICOM attributes as values.</li><li>We introduced how to use some of the important methods and attributes that PyDicom provides to deal with the DataSet class.</li><li>The values of a DataSet are basically a DataElement, another PyDicom class, that contains the DICOM tag, keyword, VR, and the value for each DICOM attribute.</li></ul><p><strong><em>Thanks For Reading…</em></strong></p><h3>Recommendation</h3><ul><li>For more details about <strong><em>DICOM</em></strong>, refer to this post</li></ul><p><a href="https://medium.com/@omar.ok1998/what-is-dicom-a28c5fe24c9d">What is DICOM ?</a></p><ul><li><strong><em>DICOM Metadata — A Useful Resource for Big Data Analytics:</em></strong><br>This <a href="https://healthmanagement.org/c/healthmanagement/issuearticle/dicom-metadata-a-useful-resource-for-big-data-analytics">article</a> provides an overview of new ways to represent data by combining patient access and DICOM information, advanced use of medical imaging metadata, analysis of radiation dose and image segmentation, and deep learning for feature engineering to enrich data.</li><li><strong><em>PyDicom Documentation:</em></strong> We only scratched the surface of this great package and it’s really well documented. If you want to learn more about PyDicom, refer to this <a href="https://pydicom.github.io/pydicom/stable/index.html">link</a> and try coding what you read there.</li></ul><h3>References</h3><p>[1] PyDicom Documentation, <a href="https://pydicom.github.io/pydicom/stable/old/pydicom_user_guide.html"><strong>User Guide</strong></a>, [Accessed at 25/12/2022]</p><p>[2] PyDicom Documentation, <a href="https://pydicom.github.io/pydicom/stable/guides/element_value_types.html"><strong>Element VRs and Python types</strong></a>, [Accessed at 25/12/2022]</p><p>[3] PyDicom Documentation,<strong> </strong><a href="https://pydicom.github.io/pydicom/stable/reference/index.html"><strong>API Reference</strong></a>, [Accessed at 25/12/2022]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518c1d71162" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introducing-pydicom-its-classes-methods-and-attributes-518c1d71162">Introducing PyDicom, its Classes, Methods, and Attributes.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with DICOM Using ImageIO Python Package]]></title>
            <link>https://medium.com/data-science/dealing-with-dicom-using-imageio-python-package-117f1212ab82?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/117f1212ab82</guid>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthcare-data-analytics]]></category>
            <category><![CDATA[dicom]]></category>
            <category><![CDATA[healthcare-data]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 19:09:18 GMT</pubDate>
            <atom:updated>2022-12-23T19:09:18.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>Medical Images == DICOM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X2ZKDX11OFPz2EIv" /><figcaption>Photo by <a href="https://unsplash.com/@jonathanborba?utm_source=medium&amp;utm_medium=referral">Jonathan Borba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we will use the ImageIO Python package to read DICOM files, extract metadata and attributes, and plot image slices using interactive slider widgets using Ipywidgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HPRSxFaULVMGLw_77X8opg.gif" /><figcaption>The output of the final code below. [Image by the author]</figcaption></figure><h3>Background Info</h3><p>DICOM is the bread and butter of medical imaging systems. If you are a Biomedical Engineer, an IT Specialist in the healthcare field, or a <strong>Healthcare Data Scientist/Analyst</strong>, you’ve probably used or at least heard about DICOM because it’s everywhere related to medical imaging systems.</p><p>DICOM, Digital Imaging and Communications in Medicine, is a set of standards that are created to allow communication across multiple modalities, e.g. CT, MRI, Ultrasound, etc., between multiple manufacturers so that all medical machines, that are DICOM-compliant of course, can speak the same language when sending information across a network.</p><p>DICOM files usually have information other than just data of pixels. DICOM Standards provide a set of attributes to standardize the data stored in DICOM files. Each attribute has a specific data type (e.g. string, integer, float, etc.) with a fixed value representation. These attributes are called metadata. Examples of DICOM metadata:</p><ul><li><strong><em>Patient-related attributes:</em></strong> name, age, sex, etc.</li><li><strong><em>Modality-related attributes:</em></strong> modality (CT, MRI, Ultrasound, etc.), manufacturer, acquisition date, etc.</li><li><strong><em>Image-related attributes:</em></strong> shape, sampling, aspect ratio, pixel data, etc.</li></ul><blockquote><strong><em>Note</em></strong> that the image-related attributes I mentioned above are very important to understand as they are useful to implement real-world calculations on medical images. We will heavily rely on them down below. It’s preferred that you understand what each represents.</blockquote><p>There are dozens of attributes that can characterize DICOM files. So, you cannot just read all of them. You need to focus only on the attributes that you might counter during your work on a DICOM-related thing. For this purpose, I highly recommend this great <a href="https://dicom.innolitics.com/ciods">DICOM Standard Browser</a> which was built by <a href="https://innolitics.com/">Innolitics</a>, you just need to search for the attribute you want to learn about.</p><p>Now let’s get down to our business… We will use python to easily surf DICOM files. We will focus on using the (ImageIO) package to present some of the basics about DICOM files. We will discuss the following:</p><ul><li>Read DICOM files using ImageIO.</li><li>DICOM attributes, Metadata.</li><li>Access a specific DICOM attribute.</li><li>Image representation using Matplotlib package.</li><li>Stack and read multiple slices.</li><li>Understand Pixel Spacing, Shape, Slice Thickness, Aspect Ratio, and the field of view.</li><li>Build an interactive image representation along the axial, coronal, and sagittal planes using Ipywidgets.</li></ul><h3>Let’s Code</h3><p>First, let’s import the required packages. We will use (ImageIO) to deal with DICOM files, (NumPy) as the pixel data are read as a NumPy-array, and (matplotlib) to visualize the images. An additional package (Ipywidgets) is also used to build an interactive slider that we can use to scroll among multiple image slices.</p><blockquote>I’m using <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjUmOStkIP8AhWYSvEDHUOhD7QQFnoECB4QAQ&amp;url=https%3A%2F%2Fcolab.research.google.com%2F&amp;usg=AOvVaw3A5aPK2kLFzKOzb6sOckVw"><strong><em>Google Colab</em></strong></a> for coding in Python</blockquote><pre>import ipywidgets as widgets<br>import numpy as np<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>import imageio</pre><h4>DICOM Dataset</h4><p>There are alot of DICOM samples on the internet. And you can use your own DICOM files. For this blog, I chose a <a href="https://www.kaggle.com/datasets/dmisky/dlwptvolumetricdicomlung">dataset</a> of 99 slices of chest-CT scan for one patient. You can find it on Kaggle. I saved the dataset on my <a href="https://drive.google.com/drive/folders/1dbJpXVUBn0mSUxgJIqKZj4d_0thSeTW3?usp=sharing">Drive</a> so I can easily have access through GoogleColab.</p><h4>Reading DICOM Files</h4><p>You can easily read a DICOM file and store it in a variable using (.imread) from ImageIO package.</p><pre>#Reading a DICOM Image<br>im = imageio.imread(&#39;/content/drive/MyDrive/Datasets/Kaggle/DICOM/dicom_lung/000009.dcm&#39;)</pre><h4>DICOM Attributes</h4><p>Using (.meta) outputs a dictionary that contains the attributes, the metadata, of this DICOM file.</p><pre>#DICOM Metadata<br>im.meta</pre><pre>Dict([(&#39;TransferSyntaxUID&#39;, &#39;1.2.840.10008.1.2.1&#39;),<br>      (&#39;SOPClassUID&#39;, &#39;1.2.840.10008.5.1.4.1.1.2&#39;),<br>      (&#39;SOPInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.397047382026069586801778973091&#39;),<br>      (&#39;StudyDate&#39;, &#39;20100227&#39;),<br>      (&#39;SeriesDate&#39;, &#39;20100227&#39;),<br>      (&#39;AcquisitionDate&#39;, &#39;20100227&#39;),<br>      (&#39;ContentDate&#39;, &#39;20100227&#39;),<br>      (&#39;StudyTime&#39;, &#39;161937.171&#39;),<br>      (&#39;SeriesTime&#39;, &#39;162536.14 &#39;),<br>      (&#39;AcquisitionTime&#39;, &#39;162208.162527 &#39;),<br>      (&#39;ContentTime&#39;, &#39;162208.162527 &#39;),<br>      (&#39;Modality&#39;, &#39;CT&#39;),<br>      (&#39;Manufacturer&#39;, &#39;SIEMENS&#39;),<br>      (&#39;StudyDescription&#39;, &#39;CT CHEST W IV CONTRAST&#39;),<br>      (&#39;SeriesDescription&#39;, &#39;LUNG 3.0  B70f&#39;),<br>      (&#39;PatientName&#39;, &#39;C3N-00247&#39;),<br>      (&#39;PatientID&#39;, &#39;C3N-00247&#39;),<br>      (&#39;PatientBirthDate&#39;, &#39;&#39;),<br>      (&#39;PatientSex&#39;, &#39;F &#39;),<br>      (&#39;PatientAge&#39;, &#39;077Y&#39;),<br>      (&#39;StudyInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.258626612405225511766549337110&#39;),<br>      (&#39;SeriesInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.242193282649561899185427104083&#39;),<br>      (&#39;SeriesNumber&#39;, 2),<br>      (&#39;AcquisitionNumber&#39;, 2),<br>      (&#39;InstanceNumber&#39;, 1),<br>      (&#39;ImagePositionPatient&#39;, (-143.2177734375, -287.2177734375, 6.0)),<br>      (&#39;ImageOrientationPatient&#39;, (1.0, 0.0, 0.0, 0.0, 1.0, 0.0)),<br>      (&#39;SamplesPerPixel&#39;, 1),<br>      (&#39;Rows&#39;, 512),<br>      (&#39;Columns&#39;, 512),<br>      (&#39;PixelSpacing&#39;, (0.564453125, 0.564453125)),<br>      (&#39;BitsAllocated&#39;, 16),<br>      (&#39;BitsStored&#39;, 12),<br>      (&#39;HighBit&#39;, 11),<br>      (&#39;PixelRepresentation&#39;, 0),<br>      (&#39;RescaleIntercept&#39;, -1024.0),<br>      (&#39;RescaleSlope&#39;, 1.0),<br>      (&#39;PixelData&#39;,<br>       b&#39;Data converted to numpy array, raw data removed to preserve memory&#39;),<br>      (&#39;shape&#39;, (512, 512)),<br>      (&#39;sampling&#39;, (0.564453125, 0.564453125))])</pre><p>Since the metadata is stored as a dictionary, you can see the keys, the attributes’ names, of the DICOM file:</p><pre># The Attributes of the DICOM File<br>im.meta.keys()</pre><pre>odict_keys([&#39;TransferSyntaxUID&#39;, &#39;SOPClassUID&#39;, &#39;SOPInstanceUID&#39;,<br>            &#39;StudyDate&#39;, &#39;SeriesDate&#39;, &#39;AcquisitionDate&#39;, &#39;ContentDate&#39;,<br>            &#39;StudyTime&#39;, &#39;SeriesTime&#39;, &#39;AcquisitionTime&#39;, &#39;ContentTime&#39;,<br>            &#39;Modality&#39;, &#39;Manufacturer&#39;, &#39;StudyDescription&#39;, &#39;SeriesDescription&#39;,<br>            &#39;PatientName&#39;, &#39;PatientID&#39;, &#39;PatientBirthDate&#39;, &#39;PatientSex&#39;,<br>            &#39;PatientAge&#39;, &#39;StudyInstanceUID&#39;, &#39;SeriesInstanceUID&#39;,<br>            &#39;SeriesNumber&#39;, &#39;AcquisitionNumber&#39;, &#39;InstanceNumber&#39;,<br>            &#39;ImagePositionPatient&#39;, &#39;ImageOrientationPatient&#39;,<br>            &#39;SamplesPerPixel&#39;, &#39;Rows&#39;, &#39;Columns&#39;, &#39;PixelSpacing&#39;,<br>            &#39;BitsAllocated&#39;, &#39;BitsStored&#39;, &#39;HighBit&#39;, &#39;PixelRepresentation&#39;,<br>            &#39;RescaleIntercept&#39;, &#39;RescaleSlope&#39;, &#39;PixelData&#39;, &#39;shape&#39;,<br>            &#39;sampling&#39;])</pre><blockquote><strong>Note:</strong> The attributes we see here might not be the whole attributes contained in this DICOM file. This is because ImageIO deals with DICOM images as light as possible. An optional reading is to check this <a href="https://github.com/imageio/imageio/blob/c57e31c90f17d32d1b0b1fe8d45a3f274776094d/imageio/plugins/_dicom.py#L29">link</a> to see the dictionary of attributes that ImageIO supports.</blockquote><h4><strong>Access a Specific DICOM Attribute</strong></h4><p>Accessing a specific attribute, “Modality” for example, can be done like the following:</p><pre>#The Modality Attribute<br>im.meta[&#39;Modality&#39;]</pre><pre>&#39;CT&#39;</pre><h4>Image Representation Using Matplotlib Package</h4><p>Usually, the “Pixel Data” attribute has the values of pixels. Let’s access this attribute just like before:</p><pre># Access the Pixel Data attribute<br>im.meta[&#39;PixelData&#39;]</pre><pre>b&#39;Data converted to numpy array, raw data removed to preserve memory&#39;</pre><p>As it says, the pixel values are stored as a NumPy array. And this is useful because NumPy is suitable for dealing with arrays and their calculation fastly. Now let’s see the pixel values:</p><pre>#print the image Numpy-array<br>im</pre><pre>Array([[ -985,  -990,  -999, ..., -1017, -1008,  -971],<br>       [-1016,  -984,  -963, ..., -1000, -1009,  -999],<br>       [-1024, -1008,  -996, ...,  -979, -1021,  -987],<br>       ...,<br>       [ -920,  -942,  -944, ...,  -893,  -917,  -955],<br>       [ -871,  -879,  -905, ...,  -895,  -869,  -867],<br>       [ -876,  -855,  -873, ...,  -933,  -982,  -936]], dtype=int16)</pre><p>We only see a bunch of numbers where each number represents the pixel value in the <a href="https://radiology.expert/x-ray-ct-technique/ct/hounsfield-units/">Hounsfield Unit (HU)</a> form. You can slice the image array using NumPy-array indices:</p><pre>#Slicing the first 5 rows and first 5 columns<br>im[0:5, 0:5]</pre><pre>Array([[ -985,  -990,  -999,  -982, -1011],<br>       [-1016,  -984,  -963,  -978, -1005],<br>       [-1024, -1008,  -996,  -969,  -992],<br>       [-1006,  -984,  -997,  -963, -1002],<br>       [ -970,  -988, -1006,  -992,  -999]], dtype=int16)</pre><p>After understanding what Pixel Data represents, let’s show the image of these pixels.</p><pre>#Show the image with gray color-map<br>plt.imshow(im, cmap=&#39;gray&#39;)<br>#Don&#39;t show tha axes<br>plt.axis(&#39;off&#39;)<br>#Add a title to the plot<br>plt.title(&#39;Axial Slice&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*FNwEc9R1PsavWl9cnhmrxg.png" /><figcaption>Image representation using Matplotlib [Image by the author]</figcaption></figure><h4>Stack and Read Multiple Slices</h4><p>A DICOM file can have multiple frames that might be found stacked in the Pixel Data attribute. You can see that in DICOM files which have videos or colored images, RGB channels. Also, sometimes you find multiple DICOM files in one folder in which each DICOM file contains one frame, or slice, of the same patient. In this case, we have to stack these DICOM files ourselves. Fortunately, this is easily done using (.volread) from ImageIO.</p><pre>#Stacking 99 slices<br>vol = imageio.volread(&#39;/content/drive/MyDrive/Datasets/Kaggle/DICOM/dicom_lung&#39;)</pre><pre>Reading DICOM (examining files): 99/99 files (100.0%)<br>  Found 1 correct series.<br>Reading DICOM (loading data): 99/99  (100.0%)</pre><p>You can access a specific slice using array indices:</p><pre>#Access the first slice<br>vol[0,:,:]</pre><pre>Array([[ -985,  -990,  -999, ..., -1017, -1008,  -971],<br>       [-1016,  -984,  -963, ..., -1000, -1009,  -999],<br>       [-1024, -1008,  -996, ...,  -979, -1021,  -987],<br>       ...,<br>       [ -920,  -942,  -944, ...,  -893,  -917,  -955],<br>       [ -871,  -879,  -905, ...,  -895,  -869,  -867],<br>       [ -876,  -855,  -873, ...,  -933,  -982,  -936]], dtype=int16)</pre><p>Also, image representation for a single specific slice can be done just like before:</p><pre>#Show the first slice.<br>plt.imshow(vol[0,:,:], cmap=&#39;gray&#39;)<br>#Don&#39;t show the axis<br>plt.axis(&#39;off&#39;)<br>#Add a title<br>plt.title(&#39;Axial Slice&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*FNwEc9R1PsavWl9cnhmrxg.png" /><figcaption>This is the first slice of the 99 stack images. [Image by the author]</figcaption></figure><blockquote>Dealing with stacked slices is very useful for extracting other planes (Sagittal, and Coronal). Also, it is helpful for radiologists to scroll over multiple slices while diagnosing. But to show the three planes and scroll upon slices correctly, we, engineers, have to understand the meaning of the specific attributes. These attributes are Sampling, Shape, and Aspect Ratio.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*y_JuwaOiRVj21w35c66QkQ.png" /><figcaption>Human anatomy planes, transverse is the axial plane. [Image by <a href="https://commons.wikimedia.org/wiki/File:Human_anatomy_planes.svg">Wikimedia Commons</a>]</figcaption></figure><pre>#Introduce the metadata of the stacked images.<br>vol.meta</pre><pre>Dict([(&#39;TransferSyntaxUID&#39;, &#39;1.2.840.10008.1.2.1&#39;),<br>      (&#39;SOPClassUID&#39;, &#39;1.2.840.10008.5.1.4.1.1.2&#39;),<br>      (&#39;SOPInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.397047382026069586801778973091&#39;),<br>      (&#39;StudyDate&#39;, &#39;20100227&#39;),<br>      (&#39;SeriesDate&#39;, &#39;20100227&#39;),<br>      (&#39;AcquisitionDate&#39;, &#39;20100227&#39;),<br>      (&#39;ContentDate&#39;, &#39;20100227&#39;),<br>      (&#39;StudyTime&#39;, &#39;161937.171&#39;),<br>      (&#39;SeriesTime&#39;, &#39;162536.14 &#39;),<br>      (&#39;AcquisitionTime&#39;, &#39;162208.162527 &#39;),<br>      (&#39;ContentTime&#39;, &#39;162208.162527 &#39;),<br>      (&#39;Modality&#39;, &#39;CT&#39;),<br>      (&#39;Manufacturer&#39;, &#39;SIEMENS&#39;),<br>      (&#39;StudyDescription&#39;, &#39;CT CHEST W IV CONTRAST&#39;),<br>      (&#39;SeriesDescription&#39;, &#39;LUNG 3.0  B70f&#39;),<br>      (&#39;PatientName&#39;, &#39;C3N-00247&#39;),<br>      (&#39;PatientID&#39;, &#39;C3N-00247&#39;),<br>      (&#39;PatientBirthDate&#39;, &#39;&#39;),<br>      (&#39;PatientSex&#39;, &#39;F &#39;),<br>      (&#39;PatientAge&#39;, &#39;077Y&#39;),<br>      (&#39;StudyInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.258626612405225511766549337110&#39;),<br>      (&#39;SeriesInstanceUID&#39;,<br>       &#39;1.3.6.1.4.1.14519.5.2.1.7085.2626.242193282649561899185427104083&#39;),<br>      (&#39;SeriesNumber&#39;, 2),<br>      (&#39;AcquisitionNumber&#39;, 2),<br>      (&#39;InstanceNumber&#39;, 1),<br>      (&#39;ImagePositionPatient&#39;, (-143.2177734375, -287.2177734375, 6.0)),<br>      (&#39;ImageOrientationPatient&#39;, (1.0, 0.0, 0.0, 0.0, 1.0, 0.0)),<br>      (&#39;SamplesPerPixel&#39;, 1),<br>      (&#39;Rows&#39;, 512),<br>      (&#39;Columns&#39;, 512),<br>      (&#39;PixelSpacing&#39;, (0.564453125, 0.564453125)),<br>      (&#39;BitsAllocated&#39;, 16),<br>      (&#39;BitsStored&#39;, 12),<br>      (&#39;HighBit&#39;, 11),<br>      (&#39;PixelRepresentation&#39;, 0),<br>      (&#39;RescaleIntercept&#39;, -1024.0),<br>      (&#39;RescaleSlope&#39;, 1.0),<br>      (&#39;PixelData&#39;, b&#39;Deferred loading of pixel data&#39;),<br>      (&#39;shape&#39;, (99, 512, 512)),<br>      (&#39;sampling&#39;, (3.0, 0.564453125, 0.564453125))])</pre><p>Notice the differences in “shape” and “sampling” attributes for the stacked images. This is done by ImageIO reading when using (.volread).</p><h4>Understand “Shape”, “Sampling” and “PixelAspectRatio” attributes</h4><ul><li><strong><em>Shape:</em></strong> It’s simply the number of rows and columns in each slice. Since we’re dealing with multiple slices, there will be a third dimension equal to the number of slices that are stacked together. In our example, the shape of the stacked images is 99 slices, 512 rows, and 512 columns.</li></ul><pre># The shape of the stacked images in each plane<br># (Axial, Coronal, and Sagittal, respectively)<br>n0, n1, n2 = vol.shape<br># Print the ouput<br>print(&quot;Number of Slices:\n\t&quot;, &quot;Axial=&quot;, n0, &quot;Slices\n\t&quot;,<br>                               &quot;Coronal=&quot;, n1, &quot;Slices\n\t&quot;,<br>                               &quot;Sagittal=&quot;, n2, &quot;Slices&quot;)</pre><pre>Number of Slices:<br>  Axial= 99 Slices<br>  Coronal= 512 Slices<br>  Sagittal= 512 Slices</pre><ul><li><strong><em>Sampling:</em></strong> If you search for “Sampling” at DICOM Standard, you won’t get a direct answer. Because it’s a <a href="https://github.com/imageio/imageio/blob/c57e31c90f17d32d1b0b1fe8d45a3f274776094d/imageio/plugins/_dicom.py#L451">special variable</a> built in ImageIO. This Sampling combination of two attributes, SliceThickness, and PixelSpacing. SliceThickness is simply the nominal slice thickness in mm. As for the PixelSpacing attribute, it’s the physical distance, in the patient. It’s specified by a numeric pair: The first value is the row spacing in <em>mm</em>, that is the spacing between the centers of adjacent rows, or vertical spacing. The second value is the column spacing in <em>mm</em>, that is the spacing between the centers of adjacent columns, or horizontal spacing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*L3Y3PMJcYyyxn0GwhPXBUg.png" /><figcaption>PixelSapcing attribute. [Image by <a href="http://dicom.nema.org/medical/dicom/current/output/html/figures/PS3.3_10.7.1.3-1.svg">DICOM</a>]</figcaption></figure><pre># The sampling of the stacked images in each plane<br># (Axial, Coronal, and Sagittal, respectively)<br>d0, d1, d2 = vol.meta[&#39;sampling&#39;] # in mm<br># Print the output<br>print(&quot;Sampling:\n\t&quot;, &quot;Axial=&quot;, d0, &quot;mm\n\t&quot;,<br>                               &quot;Coronal=&quot;, d1, &quot;mm\n\t&quot;,<br>                               &quot;Sagittal=&quot;, d2, &quot;mm&quot;)</pre><pre>Sampling:<br>  Axial= 3.0 mm<br>  Coronal= 0.564453125 mm<br>  Sagittal= 0.564453125 mm</pre><ul><li><strong><em>Pixel Aspect Ratio:</em></strong> Ratio of the vertical size and horizontal size of the pixels in the image along a specific axis. Notice that “PixelAspectRatio” is not in the metadata of the stacked images. But that’s okay because we can calculate the aspect ratio along each axis by using the “sampling” parameters. The image below represents the PixelAspectRatio attribute.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*0ZJTGq8msFZF3qcRIr5qkQ.png" /><figcaption>PixelAspectRatio attribute. [Image by <a href="http://dicom.nema.org/medical/dicom/current/output/html/figures/PS3.3_C.7.6.3.1.7-1.svg">DICOM</a>]</figcaption></figure><pre># The aspect ratio along the axial plane<br>axial_asp = d1/d2<br># The aspect ratio along the sagittal plane<br>sagittal_asp = d0/d1<br># The aspect ratio along the coronal plane<br>coronal_asp = d0/d2<br># Print the output<br>print(&quot;Pixel Aspect Ratio:\n\t&quot;, &quot;Axial=&quot;, axial_asp, &quot;\n\t&quot;,<br>                               &quot;Coronal=&quot;, coronal_asp, &quot;\n\t&quot;,<br>                               &quot;Sagittal=&quot;, sagittal_asp)</pre><pre>Pixel Aspect Ratio:<br>  Axial= 1.0 <br>  Coronal= 5.314878892733564 <br>  Sagittal= 5.314878892733564</pre><h4>Field of View</h4><p>By multiplying the “shape” parameters by the “sampling” parameters, the physical space in <em>mm</em>, along each axis, we get the Field of View along each axis.</p><pre>print(&quot;Field of View:\n\t&quot;, &quot;Axial=&quot;, n0*d0, &quot;mm\n\t&quot;,<br>                            &quot;Coronal=&quot;, n1*d1, &quot;mm\n\t&quot;,<br>                            &quot;Sagittal=&quot;, n2*d2, &quot;mm&quot;)</pre><pre>Field of View:<br>  Axial= 297.0 mm<br>  Coronal= 289.0 mm<br>  Sagittal= 289.0 mm</pre><h4>Build an interactive image representation using Ipywidgets</h4><blockquote>Now, after understanding what sampling and shape mean, let’s use them to do a correct representation of the images with the correct aspect ratio along each axis. We’ll use Ipywidgets to build an integer slider which we can scroll between different slices of the specific planes (Axial, Sagittal, or Coronal).</blockquote><pre># Add a slider that starts with 0 and ends at the number of<br># slices along the axial plane, n0=99.<br>@widgets.interact(axial_slice=(0,n0-1))<br># Define the function that shows the images of the specified slice number.<br># It starts with the 10th slice. And you can scroll over any slice<br># using the slider.<br>def axial_slicer(axial_slice=50):<br>  fig, ax = plt.subplots(1, 1, figsize=(8, 8))<br>  # Show the image of the specified slice number in &#39;gray&#39; color-map<br>  # and axial aspect ratio<br>  ax.imshow(vol[axial_slice,:,:], cmap=&#39;gray&#39;, aspect=axial_asp)<br>  # Don&#39;t show the axis<br>  ax.axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*nazxl1xEvPhGB6uWVqgb2Q.gif" /><figcaption>Scrolling upon multiple axial slices using interactive widgets. [Image by the author]</figcaption></figure><p>Now let’s show the images of three slices each along a specific axis. I intentionally showed the axes to easily understand the shape of the slices along each axis.</p><pre># Define a figure with 1 row and 3 columns of plots to show<br># the images along the three planes<br>fig, ax = plt.subplots(1, 3, figsize=(8, 8))<br># Axial Plane: show the 10th slice<br>ax[0].imshow(vol[10,:,:], cmap=&#39;gray&#39;, aspect= axial_asp)<br>#ax[0].axis(&#39;off&#39;)<br>ax[0].set_title(&#39;Axial&#39;)<br><br># Coronal Plane: show the slice 100<br>ax[1].imshow(vol[:,100,:],cmap=&#39;gray&#39;, aspect= coronal_asp)<br>#ax[1].axis(&#39;off&#39;)<br>ax[1].set_title(&#39;Coronal&#39;)<br><br># Sagittal Plane: show the slice 100<br>ax[2].imshow(vol[:,:,100], cmap=&#39;gray&#39;, aspect= sagittal_asp)<br>#ax[2].axis(&#39;off&#39;)<br>ax[2].set_title(&#39;Sagittal&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*l3czEy4AGCZfibmi_KDOow.png" /><figcaption>Slices(10 Axial, 100 Coronal, 100 Sagittal) with the correct aspect ratio of each plane. [Image by the author]</figcaption></figure><p>Let’s try the wrong way… let’s show the images ignoring the aspect ratio of each axis.</p><pre># Define a figure with 1 row and 3 columns of plots to show the<br># images along the three planes<br>fig, ax = plt.subplots(1, 3, figsize=(8, 8))<br># Axial Plane: show the 10th slice<br>ax[0].imshow(vol[10,:,:], cmap=&#39;gray&#39;)<br>#ax[0].axis(&#39;off&#39;)<br>ax[0].set_title(&#39;Axial&#39;)<br><br># Coronal Plane: show the slice 100<br>ax[1].imshow(vol[:,100,:],cmap=&#39;gray&#39;)<br>#ax[1].axis(&#39;off&#39;)<br>ax[1].set_title(&#39;Coronal&#39;)<br><br># Sagittal Plane: show the slice 100<br>ax[2].imshow(vol[:,:,100], cmap=&#39;gray&#39;)<br>#ax[2].axis(&#39;off&#39;)<br>ax[2].set_title(&#39;Sagittal&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*MqAZIeZSIaXPqVbE9jsUug.png" /><figcaption>Slices(10 Axial, 100 Coronal, 100 Sagittal) ignoring the aspect ratio of each plane. [Image by the author]</figcaption></figure><p>We can see that only the axial plane is not messy. This is because the argument “aspect” is set to 1 by default, which is the aspect ratio of the axial plane in our case (d1/d2 = 0.564453125 / 0.564453125 = 1).</p><h4>Our Final Code</h4><p>Let’s go beyond just one slider with one image plane. We will build a figure of 3 plots that contain the three planes (Axial, Coronal, and Sagittal, respectively). We can specify the slice number using the specific slider for each plane. Don’t forget to add the correct aspect ratio so it won’t get messy just like above.</p><pre># Add three sliders that start with 0 and ends at the number of slices<br># along each plane.<br># Axial:    n0=99   slice<br># Corornal: n1=512  slice<br># Sagittal: n2=512  slice<br>@widgets.interact(axial_slice=(0,n0-1), coronal_slice=(0,n1-1),\<br>                  sagittal_slice=(0,n2-1))<br>def slicer(axial_slice, coronal_slice, sagittal_slice=100):<br>  fig, ax = plt.subplots(1, 3, figsize=(12, 12))<br><br>  # Show the specfied slice on the axial plane with &#39;gray&#39; color-map<br>  # and axial aspect ratio.<br>  ax[0].imshow(vol[axial_slice,:,:], cmap=&#39;gray&#39;, aspect= axial_asp)<br>  ax[0].axis(&#39;off&#39;)<br>  ax[0].set_title(&#39;Axial&#39;)<br><br>  # Show the specified slice on the coronal plane with &#39;gray&#39; color-map<br>  # and coronal aspect ratio.<br>  ax[1].imshow(vol[:,coronal_slice,:],cmap=&#39;gray&#39;, aspect= coronal_asp)<br>  ax[1].axis(&#39;off&#39;)<br>  ax[1].set_title(&#39;Coronal&#39;)<br><br>  # Show the specified slice on the sagittal plane with &#39;gray&#39; color-map<br>  # and sagittal aspect ratio.<br>  ax[2].imshow(vol[:,:,sagittal_slice], cmap=&#39;gray&#39;, aspect= sagittal_asp)<br>  ax[2].axis(&#39;off&#39;)<br>  ax[2].set_title(&#39;Sagittal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HPRSxFaULVMGLw_77X8opg.gif" /><figcaption>Scrolling upon multiple axial, coronal, and sagittal slices using interactive widgets. [Image by the author]</figcaption></figure><h3>Conclusion</h3><ul><li>We’ve seen how to use the ImageIO package to read DICOM files. And the power of using (.volread) to stack the images and read them more conveniently.</li><li>We’ve learned that a DICOM file has metadata, a set of attributes, along with Pixel Data. And we’ve introduced some of the basics of specific image-related attributes, such as PixelSapcing, SliceThickness, Shape, and PixelAspectRatio.</li><li>We’ve pointed out the importance of the aspect ratio parameter when plotting the images along the axes and how the image gets messy if it’s not correctly specified.</li><li>We’ve built a figure that shows the specified slice number along the axial, coronal, and sagittal planes using the slider of the Ipywidgets package.</li></ul><p><strong><em>Thanks For Reading…</em></strong></p><h3>Recommendation</h3><ul><li>For more details about DICOM: refer to the previous blog, <a href="https://medium.com/@omar.ok1998/what-is-dicom-a28c5fe24c9d"><strong><em>What is DICOM?</em></strong></a></li><li><strong><em>DICOM Metadata — A Useful Resource for Big Data Analytics:</em></strong><br>This <a href="https://healthmanagement.org/c/healthmanagement/issuearticle/dicom-metadata-a-useful-resource-for-big-data-analytics">article</a> provides an overview of new ways to represent data by combining patient access and DICOM information, advanced use of medical imaging metadata, analysis of radiation dose and image segmentation, and deep learning for feature engineering to enrich data.</li><li><a href="https://app.datacamp.com/learn/courses/biomedical-image-analysis-in-python"><strong><em>Biomedical Image Analysis in Python Course</em></strong></a> on <strong>DataCamp</strong>. This course was my first dive into DICOM images and medical image processing using Python. The information in this blog heavily depends on the first chapter of this course, which is the only free chapter.</li><li><strong><em>Ipywidget </em></strong><a href="https://ipywidgets.readthedocs.io/en/7.6.2/examples/Widget%20Basics.html"><strong><em>Documentation</em></strong></a> is a good start to learning about building interactive widgets.</li></ul><h3>References</h3><p>[1] DataCamp, First Chapter of <a href="https://app.datacamp.com/learn/courses/biomedical-image-analysis-in-python">Biomedical Image Analysis in Python Course</a>, First Chapter, Exploration.</p><p>[2] C. Rossant, <a href="https://ipython-books.github.io/">IPython Interactive Computing and Visualization Cookbook</a>, (2018), <a href="https://ipython-books.github.io/33-mastering-widgets-in-the-jupyter-notebook/">Mastering widgets in the Jupyter Notebook</a>.</p><p>[3] ImageIO, GitHub, ImageIO-Plugin-DICOM, (2022), DICOM Attributes, <a href="https://github.com/imageio/imageio/blob/c57e31c90f17d32d1b0b1fe8d45a3f274776094d/imageio/plugins/_dicom.py#L28">MINIDICT</a>.</p><p>[4] Innolitics, DICOM Standard Browser, (2022), <a href="https://dicom.innolitics.com/ciods/ct-image/image-plane/00180050">Slice Thickness Attribute</a>.</p><p>[5] Innolitics, DICOM Standard Browser, (2022), <a href="https://dicom.innolitics.com/ciods/ct-image/image-plane/00280030">Pixel Spacing Attribute</a>.</p><p>[6] Innolitics, DICOM Standard Browser, (2022), <a href="https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280034">Aspect Ratio Attribute</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117f1212ab82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dealing-with-dicom-using-imageio-python-package-117f1212ab82">Dealing with DICOM Using ImageIO Python Package</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is DICOM ?]]></title>
            <link>https://medium.com/@omar.ok1998/what-is-dicom-a28c5fe24c9d?source=rss-f8302b9534b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a28c5fe24c9d</guid>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[healthcare-data]]></category>
            <category><![CDATA[healthcare-it]]></category>
            <category><![CDATA[biomedical-engineering]]></category>
            <category><![CDATA[dicom]]></category>
            <dc:creator><![CDATA[Omar Alkousa]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 12:11:06 GMT</pubDate>
            <atom:updated>2022-12-20T04:10:21.669Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>There are literally billions of DICOM Images currently in use for clinical care!!</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*U5HWD0dc9YdUnlgjBN_L-A.png" /><figcaption>Image Source: I-MED Radiology Network</figcaption></figure><p>If you are a Biomedical Engineer, an IT Specialist in the healthcare field, or a Healthcare Data Scientist/Analyst, you’ve probably used or at least heard about DICOM because it’s everywhere related to medical imaging systems.</p><p>We will cover some of the most important information related to DICOM like:</p><ul><li>What is DICOM?</li><li>What does a DICOM Data Object contain?</li><li>Image Display Using DICOM.</li><li>DICOM Services.</li><li>A blink in the history of DICOM.</li><li>DICOMweb.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*mBV2nn3I0ml3kA4ZhZEgkA.png" /><figcaption><strong>DICOM Logo.</strong> Image <a href="https://www.dicomstandard.org/">Source</a></figcaption></figure><h4><strong>What is DICOM in General?</strong></h4><p>DICOM®, <strong>Digital Imaging and Communications in Medicine</strong>, is the international standard for medical images and related information. It defines the formats for medical images that can be exchanged with the data and quality necessary for clinical use.</p><p>DICOM® is implemented in almost every radiology and radiotherapy device (X-ray, CT, MRI, ultrasound, etc.). It is one of the world’s most widely deployed healthcare messaging standards in the world. The International Organization for Standardization recognizes it as the ISO:12052.</p><h4>What does a DICOM Data Object contain?</h4><p>DICOM groups information into data sets. That means that a file of a chest x-ray image, for example, actually contains the patient ID within the file, so that the image can never be separated from this information by mistake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*woJsXEJuH4yiTfWSgGK89A.png" /><figcaption>A DICOM object with metadata and image. Image <a href="https://www.researchgate.net/figure/DICOM-object-with-metadata-and-image-The-header-is-zoom-in-right-hand-side-and-it_fig2_260374716">Source</a></figcaption></figure><p>A DICOM data object consists of several attributes, including items such as name, ID, etc., and also one special attribute containing the image pixel data. The attribute of pixel data may contain multiple frames, allowing storage of cine loops or other multi-frame data. Therefore, three- or four-dimensional data can be encapsulated in a single DICOM object.</p><h4>Image Display Using DICOM:</h4><p>Given that many newly acquired images are digital, there is a potential to view them on any number of computer systems. Computers as common as a standard personal computer (PC) or as sophisticated as a <strong>Picture Archival and Communications System (PACS)</strong> workstation may be used to view images. The need for consistent image presentation on this wide selection of workstations has been recognized as part of a broader description of a high-quality display, which is required for medical image presentation. DICOM can promote identical grayscale image display on different monitors and consistent hard-copy images from various printers. This is done using the <strong>DICOM grayscale standard display function (GSDF)</strong>. This standard provides a mathematical definition of the luminance output versus digital input which ensures perceptually equivalent contrast throughout the grayscale range of the display.</p><h4>DICOM Services:</h4><p>DICOM consists of many services, most of which involve data transmission over a network. The most common services are:</p><ul><li><strong><em>DICOM Store Service</em></strong>, which is used to send images or other persistent objects (structured reports, etc.) to a picture archiving and communication system (PACS) or workstation. It is used to transfer DICOM images and other related digital data from a DICOM node to another DICOM node, which allows the exchange of data among multiple devices over the DICOM network.</li><li><strong><em>DICOM Storage Commitment Service</em></strong>. It is used to confirm that an image has been permanently stored by a device. It is complementary to the DICOM Storage service but more focused on the safekeeping of data concerning this last service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*I4j-Cm9BOh0L3P8vI1P6WQ.png" /><figcaption>DICOM Services. SCU refers to Service Class User. SCP refers to Service Class Provider. Image <a href="https://link.springer.com/content/pdf/10.1007/978-3-540-74571-6_2.pdf">Source</a></figcaption></figure><ul><li><strong><em>Query/Retrieve Service.</em></strong> This service enables a workstation to find lists of images or other such objects and then retrieve them from a picture archiving and communication system.</li><li><strong><em>The DICOM Verification Service</em></strong> is probably the simplest. It is used to verify DICOM connectivity between two DICOM nodes.</li><li><strong><em>Print Service</em></strong>. This service is used to send images to a DICOM Printer, for example, to print an X-Ray film. There is a standard calibration to help ensure consistency between various display devices, including hard-copy printouts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Kji0I8hBr2g80AVAjpPXkg.png" /><figcaption>DICOM Printing Service. Image <a href="https://www.neologica.it/eng/products/DICOMJet">Source</a></figcaption></figure><ul><li><strong><em>Modality Worklist.</em></strong> Today, most medical centers use information systems such as <strong>Hospital Information Systems, HIS</strong>, or <strong>Radiology Information Systems, RIS</strong>, to store patients’ demographics and exam scheduling information. These data are then required during the image acquisition phase at the acquisition modality since digital acquisition devices must know all relevant patient and study information to store them in the digital images they produce. The items in the worklist include relevant details about the subject of the procedure (patient ID, name, sex, and age), the type of procedure (equipment type, procedure description, procedure code), and the procedure order (referring physician, accession number, reason for exam). Before the use of the DICOM Modality Worklist service, the scanner operator was required to manually enter all the relevant details. Manual entry is slower and introduces the risk of misspelled patient names, and other data entry errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*A3_AAU29KsTHSeGLEJGP2w.png" /><figcaption>Modality Worklist Service. Image <a href="https://www.neologica.it/eng/Products/DICOMMod">Source</a></figcaption></figure><ul><li><strong><em>Modality Performed Procedure Step Service</em></strong>, which is a complementary service to Modality Worklist. It enables the modality to send a report about a performed examination including data about the images acquired, beginning time, end time, duration of a study, dose delivered, etc. It helps give the radiology department a more precise handle on resource (acquisition station) use.</li></ul><h4>The history of DICOM:</h4><p>It all began in 1983 when the <strong>American College of Radiology (ACR)</strong> and the <strong>National Electrical Manufacturers Association (NEMA)</strong> joined forces and formed a Standards committee to meet the combined needs of radiologists, physicists, and equipment vendors. The first standard, <strong>ACR-NEMA 300</strong>, was released in 1985. Later, in 1993 was changed to DICOM. Since then, many highlighted histories and milestones that have been going on. You can refer to this <a href="https://www.dicomstandard.org/history">link </a>for more details.</p><h4>DICOMWeb:</h4><p>DICOMweb™ is the DICOM Standard for web-based medical imaging. It is a set of <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">RESTful </a>services that enable web developers to unlock the power of healthcare images using industry-standard toolsets. DICOMweb can be implemented directly or as a proxy for the DIMSE services. <strong>DIMSE</strong> refers to <strong>DICOM Message Service Element</strong> that provides the mechanism for message exchange between peer Application Entities once an Association between them has been established. DICOMweb offers modern web-based access to DICOM-enabled systems. DICOMweb has multiple main services such as:</p><ul><li><strong><em>Query:</em></strong> Search for DICOM objects. <strong>Query-based on ID for DICOM Objects (QIDO)</strong> enables you to search for studies, series, and instances by patient ID, and receive their unique identifiers for further usage (i.e., to retrieve their rendered representations).</li><li><strong><em>Retrieve:</em></strong> Retrieve DICOM objects <strong>(WADO-RS)</strong>. Or retrieve single DICOM instances <strong>(WADO-URI)</strong>. <strong>Web Access to DICOM Objects (WADO) </strong>enables you to retrieve specific studies, series, and instances by reference.</li><li><strong><em>Store:</em></strong> <strong>STore Over the Web (STOW)</strong> enables you to store specific instances on the server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*xJSXaxmKKi6fPdtg62ki-w.png" /><figcaption>The store service (STOW-RS). Image <a href="https://www.dicomstandard.org/using/dicomweb/store-stow-rs">Source</a></figcaption></figure><ul><li><strong><em>Worklist:</em></strong> Manage worklist items <strong>(UPS-RS)</strong>. The <strong>Unified Procedure Step (UPS)</strong> enables clients to manage Workitems. It also describes how notifications (including subscriptions) work.</li><li><strong><em>Capabilities:</em></strong> Discover service enables you to discover the supported services of a particular DICOMweb end-point. The image below represents the use of the Capabilities service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*qij3AJUAuIZ_E6TvnPuREw.png" /><figcaption>The capabilities service. Image <a href="https://www.dicomstandard.org/using/dicomweb/capabilities">Source</a></figcaption></figure><p>DICOMwebTM encodes the data in <a href="https://365datascience.com/trending/json/">JSON and XML</a>. And this is useful and nicely applicable for health data scientists and machine learning developers. For more details, refer to this <a href="https://www.dicomstandard.org/using/dicomweb">link</a>. And you can check more details about DICOMweb resources and attributes by following this <a href="https://www.dicomstandard.org/docs/librariesprovider2/dicomdocuments/dicom/wp-content/uploads/2018/04/dicomweb-cheatsheet.pdf?sfvrsn=4ef48ea0_0">link </a>of DICOMweb Cheatsheet.</p><h4>Conclusion:</h4><p>DICOM is a set of standards that are created to allow communication across multiple modalities between multiple manufacturers so that all medical machines, that are DICOM-compliant of course, can speak the same language when sending information across a network. All you need is one piece of software, a DICOM reader, to read many medical DICOM images from many different modalities.</p><p>In the next blog, I will discuss <a href="https://github.com/OmarAlkousa/DICOM-Using-Python.git"><strong><em>how to deal with DICOM objects using Python</em></strong></a><strong> </strong>and dive in details beyond just pixels of images.</p><p><strong><em>Thanks For Reading…</em></strong></p><h4>Recommendation to read:</h4><p>To give you a plus ultra understanding what DICOM is and what can you do with DICOM objects, I’ll point out on some links that might be helpful.</p><ul><li><strong><em>DICOM Service in Azure Health Data Services: </em></strong>The DICOM service is a managed service within <a href="https://learn.microsoft.com/en-us/azure/healthcare-apis/healthcare-apis-overview"><strong>Azure Health Data Services</strong></a> that ingests and persists DICOM objects at multiple thousands of images per second. It facilitates communication and transmission of imaging data with any DICOMweb enabled systems or applications via DICOMweb Standard APIs like Store (STOW-RS), Search (QIDO-RS), Retrieve (WADO-RS). You can check this <a href="https://learn.microsoft.com/en-us/azure/healthcare-apis/dicom/dicom-services-overview">link</a> to see more details about DICOM Service and its great applications, especially for health data scientists and AI engineers. Don’t forget to check the GitHub <a href="https://github.com/microsoft/dicom-server">link</a> of DICOM Server on Azure.</li><li><strong><em>DICOM Metadata — A Useful Resource for Big Data Analytics:</em></strong><br>This <a href="https://healthmanagement.org/c/healthmanagement/issuearticle/dicom-metadata-a-useful-resource-for-big-data-analytics">article</a> provides an overview of new ways to represent data by combining patient access and DICOM information, advanced use of medical imaging metadata, analysis of radiation dose and image segmentation, and deep learning for feature engineering to enrich data.</li><li><strong><em>DICOM Progress:</em></strong> This <a href="https://www.dicomstandard.org/supplements">link</a> provides an overview of the yearly progress of the DICOM. Also, it provides the progress and services they are currently working on it.</li><li><strong><em>Medical Imaging I.T. Basics:</em></strong> In this <a href="https://medium.com/geekculture/medical-imaging-i-t-basics-358c57f3e7af">blog</a>, Dominic DiFrancesco introduces some of the basic elements for anyone working in healthcare I.T., including some basics of DICOM. I’m sure you’ll find it a great source to read.</li></ul><h4>References:</h4><p>[1] “DICOM Standard,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/about-home.">https://www.dicomstandard.org/about-home.</a> [Accessed 4 12 2022].</p><p>[2] “DICOM Concepts,” [Online]. Available: <a href="https://www.dicomstandard.org/concepts.">https://www.dicomstandard.org/concepts.</a> [Accessed 4 12 2022].</p><p>[3] Kenneth A. Fetterly, Hartwig R. Blume, Michael J. Flynn, and Ehsan Samei, “Introduction to Grayscale Calibration and Related Aspects of Medical Imaging Grade Liquid Crystal Displays,” <em>Journal of Digital Imaging, </em>vol. 21, no. 2, pp. 193–207, 2008.</p><p>[4] “Neologica Tutorial DICOMStorage,” Neologica, [Online]. Available: <a href="https://www.neologica.it/eng/Tutorial/DICOMStorage.">https://www.neologica.it/eng/Tutorial/DICOMStorage.</a> [Accessed 4 12 2022].</p><p>[5] “Neologica Tutorial DICOMStorageCommitment,” Neologica, [Online]. Available: <a href="https://www.neologica.it/eng/Tutorial/DICOMStorageCommitment.">https://www.neologica.it/eng/Tutorial/DICOMStorageCommitment.</a> [Accessed 4 12 2022].</p><p>[6] “Neologica Tutorial DICOMVerification,” Neologica, [Online]. Available: <a href="https://www.neologica.it/eng/Tutorial/DICOMVerification.">https://www.neologica.it/eng/Tutorial/DICOMVerification.</a> [Accessed 4 12 2022].</p><p>[7] “Neologica Products DICOMMod,” Neologica, [Online]. Available: <a href="https://www.neologica.it/eng/Products/DICOMMod.">https://www.neologica.it/eng/Products/DICOMMod.</a> [Accessed 4 12 2022].</p><p>[8] “DICOM History,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/history.">https://www.dicomstandard.org/history.</a> [Accessed 4 12 2022].</p><p>[9] “DICOMWeb,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb.">https://www.dicomstandard.org/using/dicomweb.</a> [Accessed 4 12 2022].</p><p>[10] “PyDicom DIMSE,” [Online]. Available: <a href="https://pydicom.github.io/pynetdicom/stable/reference/dimse.html.">https://pydicom.github.io/pynetdicom/stable/reference/dimse.html.</a> [Accessed 4 12 2022].</p><p>[11] “DICOMWeb Query,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb/query-qido-rs.">https://www.dicomstandard.org/using/dicomweb/query-qido-rs.</a> [Accessed 4 12 2022].</p><p>[12] “DICOMWeb Retrieve,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb/retrieve-wado-rs-and-wado-uri.">https://www.dicomstandard.org/using/dicomweb/retrieve-wado-rs-and-wado-uri.</a> [Accessed 4 12 2022].</p><p>[13]“DICOMWeb Store,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb/store-stow-rs.">https://www.dicomstandard.org/using/dicomweb/store-stow-rs.</a> [Accessed 4 12 2022].</p><p>[14] “DICOMWeb Worklist,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb/workflow-ups-rs.">https://www.dicomstandard.org/using/dicomweb/workflow-ups-rs.</a> [Accessed 4 12 2022].</p><p>[15] “DICOMWeb Capabilities,” DICOM, [Online]. Available: <a href="https://www.dicomstandard.org/using/dicomweb/capabilities.">https://www.dicomstandard.org/using/dicomweb/capabilities.</a> [Accessed 4 12 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a28c5fe24c9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>