<?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 Roberto Mena on Medium]]></title>
        <description><![CDATA[Stories by Roberto Mena on Medium]]></description>
        <link>https://medium.com/@alexandro.ramr777?source=rss-77bf5998f53e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7fvJ6xIV_OnLVs0L.jpg</url>
            <title>Stories by Roberto Mena on Medium</title>
            <link>https://medium.com/@alexandro.ramr777?source=rss-77bf5998f53e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:40:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandro.ramr777/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[How to do Bias Field Correction with Python]]></title>
            <link>https://medium.com/@alexandro.ramr777/how-to-do-bias-field-correction-with-python-156b9d51dd79?source=rss-77bf5998f53e------2</link>
            <guid isPermaLink="false">https://medium.com/p/156b9d51dd79</guid>
            <category><![CDATA[tki]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[thresholding]]></category>
            <category><![CDATA[mri]]></category>
            <dc:creator><![CDATA[Roberto Mena]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 03:08:46 GMT</pubDate>
            <atom:updated>2023-04-14T03:08:46.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*zeZ5vvIj5_Hs9tBFuFjOCw.png" /></figure><p>Chances are you are a developer or a data scientist that is working in a project that involves MRI images preprocessing. You have read several papers that mention this processing technique <strong><em>Bias Field Correction</em></strong> or<strong> N4 Bias Field correction</strong>. But you can’t find an easy tutorial to carry out this(only using Python). I hope you could found this article useful.</p><p><strong>The Problem</strong></p><p>You have one or more MRI images, files with extension .nii or .nii.gz and you need to apply Bias Field Correction to it and using only python.</p><p>Before we continue, I must say that this article assumes familiarity with Python and MRI images with .nii or .nii.gz extension.</p><p><strong>The solution</strong></p><p>First, What is Bias Field Correction?. It is a technique to improve an MRI image, by removing some noise signals in the image. These are generated by the scanner when the image is acquired. These signals are little perceptible for the human eye but of high sensitivity for processing algorithms.</p><p>The standard algorithm used it is the so called N4 Bias Field Correction. There are multiple implementations available but we will use what I consider the most practical and easiest to follow. We will use the library SimpleITK (SITK) for that purpose.</p><p><strong><em>Warning</em></strong>: The code I will describe next it is simplified version of this <a href="https://www.youtube.com/watch?v=PUs27QW5ETE">video tutorial</a> and this <a href="https://github.com/Angeluz-07/MRI-preprocessing-techniques/blob/main/notebooks/03_bias_field_correction.ipynb">jupyter notebook</a>. You are free to keep reading and/or follow up those resources.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPUs27QW5ETE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUs27QW5ETE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPUs27QW5ETE%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/93c983ae01f0a4fef035001203d87997/href">https://medium.com/media/93c983ae01f0a4fef035001203d87997/href</a></iframe><p><strong>The code</strong></p><p>From now on, the code described it is assumed to be executed in a Jupyter Notebook.</p><pre>import SimpleITK as sitk #1<br>raw_img_sitk = sitk.ReadImage(raw_img_path, sitk.sitkFloat32) #2<br>raw_img_sitk_arr = sitk.GetArrayFromImage(raw_img_sitk) #3</pre><ul><li>#1 : I import Simple ITK library.</li><li>#2 : sitk.ReadImage it is used to load a MRI image with .nii or .nii.gz extension(it can load other extensions but that it is out of the scope of the article). The variable raw_img_path, is the path of the image I want to process.</li><li>#3 : sitk.GetArrayFromImage returns a numpy array that it is the representation of the MRI image and its pixel values.</li></ul><p><strong>Create a Head Mask</strong></p><p>Something you should know about N4 bias field correction algorithm it is that is computationally expensive. So it is recommended using it with a mask. A mask is a binary image useful to delimit regions of interest(ROI) in images. In this case the ROI is the head, and we can create one very quickly with SITK.</p><pre>transformed = sitk.RescaleIntensity(raw_img_sitk, 0, 255) #1<br>transformed = sitk.LiThreshold(transformed,0,1) #2<br>head_mask = transformed</pre><ul><li>#1 : sitk.RescaleIntensity, only used to rescale any intensity(pixel value) out of the scale of 0–255</li><li>#2 : sitk.LiThreshold, it is where the head mask it is generated, this is a thresholding operation. Any other thresholding algorithm should work ok.</li></ul><p><strong>Bias Field Correction</strong></p><pre>shrinkFactor = 4 #1<br>inputImage = raw_img_sitk<br><br>inputImage = sitk.Shrink( raw_img_sitk, [ shrinkFactor ] * inputImage.GetDimension() ) #2<br>maskImage = sitk.Shrink( head_mask, [ shrinkFactor ] * inputImage.GetDimension() ) #3<br><br>bias_corrector = sitk.N4BiasFieldCorrectionImageFilter() #4<br><br>corrected = bias_corrector.Execute(inputImage, maskImage) #5</pre><ul><li>#1 : Remember the algorithm is computationally expensive, so we apply the algorithm with a shrinked version of the image. We use a shrink factor to control how much the image will be shrinked.</li><li>#2 : We use the function sitk.Shrink, we pass the raw image, we pass as input the multiplication of the shrink factor by the dimension of the image. This is how we use the function sitk.Shrink.</li><li>#3 : We also shrink the head mask image generated previously with same parameters.</li><li>#4 : We define an object sitk.N4BiasFieldCorrectionImageFilter() to do the operation.</li><li>#5 : Here we execute the correction, we pass the raw image, and the mask image. <em>Be aware that we are passing the shrinked versions.</em></li></ul><p><strong>Get Corrected Image in original Resolution</strong></p><p>We have applied the correction over a shrinked version, now it is time to get the corrected image in the original resolution(the size before we shrinked the image). We should do the following:</p><pre>log_bias_field = bias_corrector.GetLogBiasFieldAsImage(raw_img_sitk) #1<br>corrected_image_full_resolution = raw_img_sitk / sitk.Exp( log_bias_field ) #2</pre><ul><li>#1 : We use the instance of the bias corrector and call the method bias_corrector.GetLogBiasFieldAsImage() passing the raw image. We get a log bias field of the image.</li><li>#2 : We divide the raw image over the result of applying the sitk.Exp() function to the log bias field of the image. <strong><em>This is where we get the corrected image at the original resolution.</em></strong></li></ul><p><strong>Save the image</strong></p><pre>sitk.WriteImage(corrected_image_full_resolution, out_path) #1</pre><ul><li>#1 To save the image we use the function sitk.WriteImage(), we pass the corrected_image_full_resolution variable and variable out_path which it is a string defining the path to save the image.</li></ul><p>Now you know how to apply Bias Field Correction to an MRI image, using only Python and the library Simple ITK.</p><p><strong>Closing Remarks</strong></p><ul><li>I tried to be as concise as possible and didnt get into the details of all the functions. This tutorial is the written version of a <a href="https://www.youtube.com/watch?v=PUs27QW5ETE">video tutorial</a> of my <a href="https://www.youtube.com/playlist?list=PLI3eIHxETjX4a5NMmgayg3wuM232fYIxy">free course on youtube</a>. There you can find more videos with a more detailed explanation of this and other processing techniques. Also you can find the notebook of this tutorial <a href="https://github.com/Angeluz-07/MRI-preprocessing-techniques/blob/main/notebooks/03_bias_field_correction.ipynb">here</a>.</li><li>There are some linux based tools available to make this operation. This tutorial has the advantage that uses only python and it is easier to follow what it is happening on each step in comparison with other tools.</li><li>This tutorial was based on this original <a href="https://simpleitk.readthedocs.io/en/master/link_N4BiasFieldCorrection_docs.html">example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156b9d51dd79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fill missing values using MongoDB aggregation framework]]></title>
            <link>https://medium.com/@alexandro.ramr777/fill-missing-values-using-mongodb-aggregation-framework-f011114e83e0?source=rss-77bf5998f53e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f011114e83e0</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[sensor-data-analysis]]></category>
            <category><![CDATA[data-aggregation]]></category>
            <dc:creator><![CDATA[Roberto Mena]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 17:20:05 GMT</pubDate>
            <atom:updated>2020-05-16T19:12:03.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fill missing values in MongoDB aggregation framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9dvBv85Mp5a6WOLbcGnuA.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@michaelhull?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Michael Hull</strong></a><strong> on </strong><a href="https://unsplash.com/photos/5z5XKYYVdLU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><p>I recently worked in a project where I had to develop different charts with aggregated data. Standard charts as <strong><em>Average values per hour</em></strong>, <strong><em>Average values per date</em> and <em>Average values per month</em></strong>. I learned to work with the M<a href="https://docs.mongodb.com/manual/aggregation/"><em>ongoDB aggregation framework</em></a> and I had to deal with missing values.</p><p>It was a very hard task to deal with missing values in application code, until I found <a href="https://stackoverflow.com/questions/52235027/fill-missing-dates-in-records"><em>this question</em></a> in <em>stackoverflow</em> and I learned how to fill missing values directly using the aggregation framework. In this article I will go step by step explaining the answer and how I applied it to fill missing values after aggregate values per hour.</p><p><strong>Attention</strong>: This article assumes basic familiarity with the M<a href="https://docs.mongodb.com/manual/aggregation/"><em>ongoDB aggregation framework</em></a>.</p><p><strong>A former definition: </strong>the MongoDB aggregation framework is basically a set of transformations applied to a collection. Transformations are expressed in JSON. These transformations happen in phases, or better-known as “stages” in MongoDB.</p><h3><strong>The problem</strong></h3><p>Let’s say we have a collection with sensor data like the following :</p><pre>[<br>   { timestamp: 1566016729, value: 20 },<br>   { timestamp: 1566018729, value: 21 },<br>   { timestamp: 1566019729, value: 24 },<br>   ...<br>]</pre><p>And we want: “B<strong>etween two dates, get the average of the field value per hour”</strong>.</p><p>Using the MongoDB aggregation framework, and two dummy timestamps, of start date and end date respectively, we would do something like this:</p><pre>db.getCollection(&#39;Sensor&#39;).aggregate([<br>{   <br>   $match : {<br>      $and :[ { &quot;timestamp&quot; : { $gte : 1566016729 } },<br>              { &quot;timestamp&quot; : { $lte : 1569962886 } } ]<br>   }<br>},<br>{<br>   $addFields : { <br>      &quot;date&quot; : { $toDate : { $multiply : [&quot;$timestamp&quot;,1000] } }<br>   }<br>},<br>{<br>   $group : {<br>     _id       : { hour : {  $hour :  &quot;$date&quot; } },<br>     &quot;average&quot; : { $avg : &quot;$value&quot; }<br>   }<br>},<br>{<br>   $project : {<br>      _id     : 0 ,<br>      hour    : &#39;$_id.hour&#39;,<br>      average : 1<br>   }<br>},<br>])</pre><p>Up to here, we would have the result as desired. But there is limitation. Let’s suppose that between the dates, only were values in the first hour of the day. This is the output we would expect:</p><pre>[<br>   { &quot;average&quot; : 33.05 ,&quot;hour&quot; : 1  },<br>   { &quot;average&quot; : null  ,&quot;hour&quot; : 2  },<br>   { &quot;average&quot; : null  ,&quot;hour&quot; : 3  },<br>   ...<br>   { &quot;average&quot; : null  ,&quot;hour&quot; : 24 }<br>]</pre><p>But this is what we actually get:</p><pre>[ { &quot;average&quot; : 33.05 ,&quot;hour&quot; : 1} ]</pre><p>We could fill missing values in application code, but is something very hard to debug and maintain, especially when we have to deal with dates and timezones. So, why not do it directly in the MongoDB aggregation.</p><h3>The solution</h3><p>We have to add extra stages in the aggregation. Alone, these stages could not make that much sense, but together and sequentially applied gave us the result desired.</p><p>I will explain the extra stages one by one:</p><p><strong><em>i.</em></strong> This stage, groups all values in a unique object. Whose _id is equal to null and the field points is an array where all the objects of the previous stage get appended .</p><pre>{<br>   $group: {<br>      _id: null,<br>      points: { $push: &quot;$$ROOT&quot; }<br>   }<br>}</pre><p><strong><em>ii.</em></strong> This stage starts from creating an array from 1 to 24. I will iterate over each value using the variable hour (also referred as $$hour). For each value from 1 to 24, gets the index of that value in the original array using the command$indexOfArray . If such value exists in our original array the result will the be actual index, otherwise it will be -1 . This index will be stored in the variable hourIndex (also referred as $$hourIndex).</p><p>Later, we check if this index was different from -1 which indicates there was a value in our original array. If so, let the original object pass (with the command $arrayElementAt and the index we found prior, $$hourIndex). If equal to -1 means, there was no such value and we have to create a new object. This takes place in the else branch of the$cond command.</p><pre>{<br>   $project :{<br>      points : {<br>         $map :{<br>            input : { $range : [ 1, 25 ] }, <br>            as : &quot;hour&quot;,<br>            in : {<br>               $let: {<br>                  vars: { <br>                      hourIndex: { <br>                         &quot;$indexOfArray&quot;:[ &quot;$points.hour&quot;,&quot;$$hour&quot; ]<br>                      } <br>                  },<br>                  in: {<br>                    $cond: {<br>                       if: { $ne:[ &quot;$$hourIndex&quot;, -1 ] },<br>                       then: {<br>                         $arrayElemAt: [ &quot;$points&quot;,&quot;$$hourIndex&quot; ]<br>                       },<br>                       else: { hour: &quot;$$hour&quot;, average: null }<br>                    }<br>                  }<br>               }<br>            }<br>         }<br>      }<br>   }<br>}</pre><p><strong><em>iii.</em></strong> Here we expand all the objects that were shrunk into a single field when we created the field points in the stage i .</p><pre>{ <br>   $unwind :  &quot;$points&quot; <br>}</pre><p><strong><em>iv.</em></strong> Up to here we carried the id: _null and our result is nested. This stage is the last step to put our values as the original input.</p><pre>{<br>   $replaceRoot: {  <br>      newRoot: &quot;$points&quot;<br>   }<br>}</pre><p>Our final query would be:</p><pre>db.getCollection(&#39;Sensor&#39;).aggregate([<br>{   <br>   $match : {<br>      $and :[ { &quot;timestamp&quot; : { $gte : 1566016729 } },<br>              { &quot;timestamp&quot; : { $lte : 1569962886 } } ]<br>   }<br>},<br>{<br>   $addFields : { <br>      &quot;date&quot; : { $toDate : { $multiply : [&quot;$timestamp&quot;,1000] } }<br>   }<br>},<br>{<br>   $group : {<br>     _id       : { hour : {  $hour :  &quot;$date&quot; } },<br>     &quot;average&quot; : { $avg : &quot;$value&quot; }<br>   }<br>},<br>{<br>   $project : {<br>      _id     : 0 ,<br>      hour    : &#39;$_id.hour&#39;,<br>      average : 1<br>   }<br>},<br>{<br>   $group: {<br>      _id: null,<br>      points: { $push: &quot;$$ROOT&quot; }<br>   }<br>},<br>{<br>   $project :{<br>      points : {<br>         $map :{<br>            input : { $range : [ 1, 25 ] }, <br>            as : &quot;hour&quot;,<br>            in : {<br>               $let: {<br>                  vars: { <br>                      hourIndex: { <br>                         &quot;$indexOfArray&quot;:[ &quot;$points.hour&quot;,&quot;$$hour&quot; ]<br>                      } <br>                  },<br>                  in: {<br>                    $cond: {<br>                       if: { $ne:[ &quot;$$hourIndex&quot;, -1 ] },<br>                       then: {<br>                         $arrayElemAt: [ &quot;$points&quot;,&quot;$$hourIndex&quot; ]<br>                       },<br>                       else: { hour: &quot;$$hour&quot;, average: null }<br>                    }<br>                  }<br>               }<br>            }<br>         }<br>      }<br>   }<br>},<br>{ <br>   $unwind :  &quot;$points&quot; <br>},<br>{<br>   $replaceRoot: {  <br>      newRoot: &quot;$points&quot;<br>   }<br>}<br>])</pre><h3>What else is possible?</h3><p>We could extend this idea in the case of make aggregation by months, i.e. <strong>between two dates, get the average of the field value per month. And fill with null, in months where there was no value.</strong></p><p>Also by dates, <strong>between two dates, get the average of the field value per date. And fill with nulls, in dates where there was no value. </strong>In the case of dates, it would be necessary(easier) generate a date-range using application code.</p><p>Once understood how this process works, we could always fill with null values as needed, given certain aggregation.</p><h3>Closing Remarks</h3><ul><li>The original solution of this process comes from <a href="https://stackoverflow.com/questions/52235027/fill-missing-dates-in-records">this question</a> in stackoverflow and was explained to fill missing values, after aggregating data by dates. I have only tried to explain what the query does, and how to apply it to other type of aggregations.</li><li>We could save us the extra stages and doing it using application code. But from my experience in this project, these aggregation queries are easier to debug and maintain. If there is an error, we could debug the query isolated from the application stack. Using some tool like <a href="https://robomongo.org/"><em>robo3T</em></a><em> </em>, we<em> </em>could add, remove and edit stages as needed to see how data is being transformed. Once we are satisfied with the aggregation query, is just a matter of translate the aggregation query using a MongoDB driver.</li><li>This idea could be extended to fill null values for several kind of aggregations(per hour, per month, per minute, per year).</li><li>Please, let me know in comments if this solution helped you ;) .</li></ul><h3>References</h3><p>Original idea about how to do the aggregation, comes mainly from :</p><ul><li><a href="https://stackoverflow.com/questions/52235027/fill-missing-dates-in-records">https://stackoverflow.com/questions/52235027/fill-missing-dates-in-records</a></li><li><a href="https://stackoverflow.com/questions/26406944/mongodb-aggreagte-fill-missing-days">https://stackoverflow.com/questions/26406944/mongodb-aggreagte-fill-missing-days</a></li></ul><p>Software used to develop, test and debug the aggregation queries:</p><ul><li><a href="https://robomongo.org/download">robo3t</a></li></ul><p>The Mongo DB aggregation framework:</p><ul><li><a href="https://docs.mongodb.com/manual/aggregation/">https://docs.mongodb.com/manual/aggregation/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f011114e83e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>