<?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 Misha Iakovlev on Medium]]></title>
        <description><![CDATA[Stories by Misha Iakovlev on Medium]]></description>
        <link>https://medium.com/@misha_92219?source=rss-8cf0f450e791------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fUWMiUvKNxu2aKqhwuvV_Q.jpeg</url>
            <title>Stories by Misha Iakovlev on Medium</title>
            <link>https://medium.com/@misha_92219?source=rss-8cf0f450e791------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@misha_92219/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[Has AlphaFold 2 Solved Protein Folding?]]></title>
            <link>https://medium.com/fuzzylabsai/has-alphafold-2-solved-protein-folding-1182536605e1?source=rss-8cf0f450e791------2</link>
            <guid isPermaLink="false">https://medium.com/p/1182536605e1</guid>
            <category><![CDATA[protein-folding]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[alphafold]]></category>
            <dc:creator><![CDATA[Misha Iakovlev]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 15:26:42 GMT</pubDate>
            <atom:updated>2020-12-02T15:26:42.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*Dc5usaWym6tcCtjGk_b21Q.png" /><figcaption>3D structure of the signalling domain of the murine Sonic hedgehog protein | Source: Wikimedia (<a href="https://commons.wikimedia.org/wiki/File:Shh_structure.png">https://commons.wikimedia.org/wiki/File:Shh_structure.png</a>)</figcaption></figure><p>At a bi-annual protein structure prediction competition <a href="https://predictioncenter.org/casp14/index.cgi">CASP14</a> DeepMind presented their <a href="https://deepmind.com/blog/article/alphafold-a-solution-to-a-50-year-old-grand-challenge-in-biology">second version of AlphaFold</a>. It outperformed other models at CASP13 in 2018, and it shows even better results this year, scoring 92.4 GDT (Global Distance Test) overall across all targets, and 87.0 GDT in free-modelling category (the most challenging one).</p><p>I am an MSc in Bioinformatics, and I have been involved in a project working on predicting effects of mutations using protein structures. So, as a person that had some experience on the topic, I decided to write down some notes regarding the recent AlphaFold news.</p><p>Protein structure prediction is prediction of a secondary and tertiary (3D) structure of a protein from its sequence of amino acids. This problem has been proven particularly hard to solve, but highly important for medicine and biotechnology. Protein structure determines how it acts and what it interacts with. For example, if we know a structure of a protein that is known to be involved in some illness, we can design drugs that interacts with this protein in order to try to treat this illness. However, determining protein structures experimentally is time consuming and expensive, so computational structure prediction would come in handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*ELUpHJVZEf0uBP5EykvlFQ.png" /><figcaption>Protein structure prediction is quite hard | Source: xkcd (<a href="https://xkcd.com/1430/">https://xkcd.com/1430/</a>)</figcaption></figure><p>Several news outlets have declared that it’s a “scientific breakthrough” and that it “solves the problem of protein folding”. However, not to belittle DeepMind’s achievement, such claims might be an overstatement for a few reasons.</p><p>First and foremost, even though they’ve shown amazing results at both CASP13 and CASP14, <strong>their model remains closed</strong>. It means, that no other research group (to the best of my knowledge) can effectively use this model, and hence the scientific community cannot directly benefit from these findings, as opposed to the other models that are available as source code, or, at least, as a server, such as <a href="http://www.sbg.bio.ic.ac.uk/phyre2/html/page.cgi?id=index">Phyre2</a> or <a href="https://zhanglab.ccmb.med.umich.edu/I-TASSER/">I-TASSER</a>.</p><p>This is <strong>not an end-to-end AI/Deep Learning</strong> protein folding system. To the best of my understanding, the model predicts spatial constraints of a protein, that are then modelled into a 3D structure using more conventional approaches (AlphaFold 1 used <a href="https://en.wikipedia.org/wiki/Limited-memory_BFGS">L-BFGS</a>).</p><p>A word on CASP itself. Even though, some benchmark is better than none, the real world results might differ significantly from what has been shown at CASP. Hence, we need to be cautious, it might well be the case that a model that shows great results at CASP, then produces a subpar output for more exotic protein targets. There exist other assessments, such as <a href="https://cameo3d.org/">CAMEO3D</a>, that evaluate methods on a continuous basis and wider range of targets, however AlphaFold does not participate in it.</p><p>And as usual, it needs to be noted that protein structure prediction is definitely important, but it <strong>does not cover the dynamics of proteins. </strong>This fact is quite important, if one considers using such models (and them alone), for example, for drug development.</p><p>Nevertheless, I will be waiting for a full paper explaining AlphaFold 2. According to their abstract, they use attention-based methods (i.e. transformers, that yielded great results in the field of NLP in a form of GPT and BERT), which sounds like an interesting approach.</p><p>I am by no means an expert in the field, but I have had some exposure to structural biology in the past. Questions and corrections are welcome.</p><p>P.S. For an interested reader, there’s <a href="https://academic.oup.com/bioinformatics/article/35/22/4862/5497249?guestAccessKey=52c36765-068a-44d9-8b6f-ab9f0d07119b">an article by Mohammed AlQuraishi</a> assessing AlphaFold at CASP13 and its importance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1182536605e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzzylabsai/has-alphafold-2-solved-protein-folding-1182536605e1">Has AlphaFold 2 Solved Protein Folding?</a> was originally published in <a href="https://medium.com/fuzzylabsai">Fuzzy Labs Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing the Stryd — running linear models]]></title>
            <link>https://medium.com/fuzzylabsai/reversing-the-stryd-running-linear-models-949675a1561f?source=rss-8cf0f450e791------2</link>
            <guid isPermaLink="false">https://medium.com/p/949675a1561f</guid>
            <category><![CDATA[wearables]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Misha Iakovlev]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 15:19:00 GMT</pubDate>
            <atom:updated>2020-11-02T20:45:38.655Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reversing the Stryd — running linear models</h3><p><em>The code and data used for the analysis can be found on </em><a href="https://github.com/fuzzylabs/wearable-my-foot/blob/master/notebooks/stryd_correlation.ipynb"><em>Github</em></a></p><p>This blog is part of our ongoing series documenting <a href="https://wearablemyfoot.tech/"><em>W</em>earable <em>My Foot</em></a>, our ongoing R&amp;D project to build a wearable fitness device powered by data science and machine learning. Today we’re looking at exercise data from <a href="https://www.stryd.com/">Stryd</a>, a commercially-available fitness tracker for runners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HW5ffXce4LRc34nalKyHw.png" /></figure><p>Stryd accurately records speed, cadence and running power over the course of a run. Because running power is a particularly useful metric for serious runners, we want to extract raw data from Stryd and understand how running power is related to other metrics, such as pace and cadence.</p><p>In a <a href="https://fuzzylabs.ai/blog/running-power-accelerometer">previous blog post</a> we started to build a procedure from the ground up using a physical model called <a href="http://www.georgeron.com/2017/12/stryd-running-power-model.html">EESA</a>. Although the model seems complex, it boils down to a few key inputs, like horizontal and vertical speed, and some reasonable assumptions about the physics behind running. This model is great in theory but presents some difficulties when faced with the realities of noisy sensor data. This time, we take a step back from the physics and see if we can ‘blindly’ model running power by analysing correlations between the values Stryd outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Vnc0rmpzd-_w_0_VMZIiVQ.jpeg" /><figcaption><a href="https://www.linkedin.com/in/tom-stockton-37a5644/">Tom</a> ready to collect data. Also visible are some highly fashionable socks</figcaption></figure><h3>Data and metrics</h3><p>To begin with, let’s go through what Stryd gives us to work with. Units for each variable are given in brackets.</p><ul><li>Power (W) — running power estimate; <strong>this is what we want to estimate.</strong></li><li>Cadence (spm) — number of steps/strides per minute.</li><li>Vertical oscillation — amplitude of oscillation of a foot along the vertical axis, or in other words how high the foot rises at its peak.</li><li>Stance time (ms) — the duration of time the foot is on the ground (sometimes called ground time or contact time).</li><li>Air power (W) — estimated power of air resistance.</li><li>Leg spring stiffness (N/m) — Stryd models the leg as a compressed spring. The ‘spring stiffness’ measures how well a runner recycles energy as their foot hits the ground (<a href="https://blog.stryd.com/2019/12/05/the-secret-of-running-run-smart-to-run-faster/">https://blog.stryd.com/2019/12/05/the-secret-of-running-run-smart-to-run-faster</a>).</li><li>Speed (m/s)</li><li>Altitude (m)</li><li>Distance (m)</li></ul><p>Ultimately all of these metrics are derived from a small number of sensors, including an accelerometer, gyroscope, altimeter, and wind meter. Except for the last two, we are using all the metrics as is. Altitude and distance, on the other hand, are absolute quantities that depend on time, and in those cases we’re really interested in is the differential— the change in the variable over time.</p><h3>Data collection</h3><p>For our experiments, we have recorded several runs under different conditions:</p><ul><li>Straight line and non-straight line paths</li><li>Running on flat and inclined surfaces</li></ul><p>Giving us 1138 data points (measurements) in total. However, we remove all data points where measured power is close to zero, under the assumption that the runner was standing still at these times, which brings us down to 949 data points to experiment with.</p><h3>Exploratory analysis</h3><p>First of all we want to see if the data that we will use to fit the model makes sense, i.e. does it show correlation where we would expect them, as well as ensuring that there’s not too much noise in the data.</p><p>To start with let’s plot all pairings of these variables to see if any patterns jump out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObHRMWma3CHcOa2TPAcpaQ.png" /><figcaption>A pair plot of a selection of variables in the data</figcaption></figure><p>We’re looking for any variables that correlate strongly with power. For instance, the speed-power graph looks like we can draw a straight line through it and that suggests that speed is a good predictor of power.</p><p>We get a clearer picture by plotting the matrix of correlation coefficients, which indicate how strongly two variables are correlated. For instance, if the coefficient for speed with power is 0.8, then we know that speed is 80% correlated with power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*3610TfysDVJz9vXshj_e1A.png" /><figcaption>Correlation matrix</figcaption></figure><p>Some variables have strong correlation to power: namely cadence, stance time, air power and speed; all of which are expected according to EESA model.</p><p>Now that we have a broad idea of what kinds of correlation to expect, now we can try fitting a number of different models. From here on it gets quite detailed, so feel free to skip to the conclusions at the end.</p><h3>Experimental design</h3><p>For this experiment we are trying to fit a linear model i.e. an equation of the form y = sum(w_i * x_i) + b , where y is our target variable (power), x_i and w_i are the features and the weight associated with them, and b is the intercept. (weights are sometimes called coefficients when talking about linear models).</p><p>Put visually, rather than algebraically, we want to find a straight line that fits the data as closely as possible, under the assumption that it is indeed possible to fit a line to the data at all. We’ll need to try a few different approaches and test their accuracy.</p><h4>Feature engineering</h4><p>The target output is power, but we need to decide what input features to use. It makes sense to narrow the original features down to only those that we expect to be used in power calculation from the EESA model, and that we are potentially able to calculate from acceleration:</p><ul><li>Cadence</li><li>Vertical oscillation</li><li>Stance time</li><li>Speed</li></ul><p>An extra quirk of the EESA model is that we expect power to be related to the <em>square</em> of speed, rather than the speed itself. Therefore we’ll create some derived features that allow us to include things like speed squared.</p><p>Feature engineering is a big topic in data science. There are many articles on this topic, for instance <a href="https://towardsdatascience.com/feature-engineering-for-machine-learning-3a5e293a5114">https://towardsdatascience.com/feature-engineering-for-machine-learning-3a5e293a5114</a>.</p><h4>Performance assessment</h4><p>To assess the performance of our models, we are using two metrics. First, the coefficient of determination, or R², is a proportion of the target variance that can be predicted from the input features (values closer to 1.0 are better), which is a standard metric to assess linear regression performance. Second, mean absolute error, MAE, which serves as an intuitive measure of how much we deviate from the expected value for running power.</p><p>As is common practice we assess the performance by splitting the data into a training and a testing sets, fitting a model on the training data, and calculating metrics using the testing and predicted values of power. However, a single train-test split might not be representative of the underlying data (due to a random nature of splitting). We can use <a href="https://machinelearningmastery.com/k-fold-cross-validation/">5-fold cross-validation</a> instead: split data into 5 chunks of the same size, fit 5 models using each chunk for testing once, and taking mean average of the performance metrics.</p><h3>Linear regression and Ordinary Least Squares</h3><p>The simplest variant of linear regression fitting method is called Ordinary Least Squares. This method minimises the residual sum of squares between the observed target (i.e. the measurements of power according to Stryd) and the values predicted by a model.</p><p>Fitting linear regression with all three feature sets, we get the following results:</p><pre>|            |   mae_mean |   r2_mean |<br>|:-----------|-----------:|----------:|<br>| Original   |   -19.112  |  0.60626  |<br>| Selected   |   -23.658  |  0.384907 |<br>| Polynomial |   -21.7786 |  0.25584  |</pre><p>The results show the best performance for a model fitted with the original features (according to both metrics), suggesting that our feature engineering attempts might not be beneficial for predicting our target.</p><h3>Regularisation</h3><p>Beyond Ordinary Least Squares there are a set of methods that use <em>regularisation. </em>Regularisation aims to avoid a model overfitting, which it does by constraining the learned coefficients.</p><h4>Ridge</h4><p>Ridge can be thought of as an extension of Ordinary Least Squares, that, in addition to minimising the error, also applies a penalty for the size of the coefficients (w_i). In contrast with OLS, Ridge requires the complexity parameter alpha (how much the size of coefficients should be penalised). We do not have a prior knowledge of what is the best value for alpha in our case, so we have to perform the parameter tuning. Thankfully, we only have one parameter to tune, so we can simply take a range of alpha values and pick one that gives the best performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*eeOyibr4MExOvqb23TJb6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*FJcN7iAXApRfS5e0OSbb4Q.png" /></figure><p>We fit Ridge linear regression using the original and polynomial features.</p><p>In both cases we see an improvement in performance, in respect to the performance of OLS. The improvement is more significant for the set of polynomial features bringing it from R² value 0.26 to 0.54.</p><pre>|            |   mae_mean |   r2_mean |<br>|:-----------|-----------:|----------:|<br>| Original   |   -19.1893 |  0.618525 |<br>| Polynomial |   -20.2247 |  0.537264 |</pre><h4>Lasso</h4><p>Another regularisation option that we have is Lasso, that penalises for non-zero coefficients, effectively trying to find a model that can explain a target with the smallest number of features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*jxNFHkrvEIMqM9Nezh9w4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*aLP7b0LKLdJQyvvBFi9U2Q.png" /></figure><p>As with the previous methods, we fit it with the original and the polynomial features. In both cases, it gives even greater improvement in performance than Ridge, resulting in the Lasso model with the original feature set the overall best performance model.</p><pre>|            |   mae_mean |   r2_mean |<br>|:-----------|-----------:|----------:|<br>| Original   |   -19.0823 |  0.638604 |<br>| Polynomial |   -19.2318 |  0.615413 |</pre><h3>Results</h3><p>As mentioned previously the overall top performing model is given by Lasso fitted with the original features (R² = 0.64, MAE = 19.08). Let’s explore this model further.</p><pre>|                                     |   mae_mean |   r2_mean |<br>|:------------------------------------|-----------:|----------:|<br>| Ordinary Least Squares              |   -19.112  |  0.60626  |<br>| Ordinary Least Squares (Selected)   |   -23.658  |  0.384907 |<br>| Ordinary Least Squares (Polynomial) |   -21.7786 |  0.25584  |<br>| Ridge                               |   -19.1893 |  0.618525 |<br>| Ridge (Polynomial)                  |   -20.2247 |  0.537264 |<br>| Lasso                               |   -19.0823 |  0.638604 |<br>| Lasso (Polynomial)                  |   -19.2318 |  0.615413 |</pre><p>The table below shows non-zero coefficients. The fitted coefficients align with our expectations:</p><pre>| Feature              | Coefficient |<br>|:---------------------|------------:|<br>| Vertical Oscillation |  1.2142     |<br>| Stance Time          | -2.23361    |<br>| Air Power            |  4.12725    |<br>| Leg Spring Stiffness | 10.407      |<br>| Speed                | 28.0068     |<br>| Altitude Diff        | 13.6        |<br>| Distance Diff        | -0.652722   |</pre><ul><li>Power is greater for greater vertical oscillation amplitude, speed, air power, and incline gradient</li><li>Low stance time and high leg spring stiffness (which are negatively correlated to each other) mean greater power</li></ul><p>However, only a subset of these features can be (potentially) inferred purely from acceleration: vertical oscillation, stance time, speed and change in distance. Constructing a model with only this variables (their respective coefficients) gives us a good starting point for calculating power using raw accelerometer data.</p><p>This approach, however, has a few limitations:</p><ul><li>Data collection: the range of different conditions that we captured is somewhat limited, included the limited range of power values, and this linear model, most probably, will not account for the cases under severely different conditions.</li><li>The Stryd’s power measurement depends on the speed, both according to correlation and the fitted model, rather than on the square of speed, which we expect from the EESA. Which might indicate some bias, that we, so far, were not able to capture or discover.</li><li>We will not be able to infer from acceleration some of the features (such as air power) that have a high influence on total power.</li></ul><h3>Conclusions</h3><p>With very little attention being paid to the underlying physics we’re able to estimate power somewhat accurately through a linear model. However we would still need to calculate certain values that are not easily derived from acceleration alone.</p><p>Speaking more broadly, the <a href="https://wearablemyfoot.tech/">Wearable My Foot</a> project can currently work out step counts and speed/cadence using acceleration in combination with some clever numerical techniques. While the approach described in this article allows us to estimate running power over short time windows, it turns out to break down when faced with longer time periods that involve a lot of elevation change. Further research is needed before we can give a proper account of running power.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949675a1561f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzzylabsai/reversing-the-stryd-running-linear-models-949675a1561f">Reversing the Stryd — running linear models</a> was originally published in <a href="https://medium.com/fuzzylabsai">Fuzzy Labs Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring Running Power with Accelerometer]]></title>
            <link>https://medium.com/fuzzylabsai/measuring-running-power-with-accelerometer-685839604798?source=rss-8cf0f450e791------2</link>
            <guid isPermaLink="false">https://medium.com/p/685839604798</guid>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Misha Iakovlev]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 06:07:21 GMT</pubDate>
            <atom:updated>2020-09-07T06:07:21.372Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The code is avalible on </em><a href="https://github.com/fuzzylabs/wearable-my-foot/"><em>Github</em></a><em>.</em></p><p>For exercises such as running and cycling, power output provides an unbiased metric for effort as compared to, for example, speed, irrespective of external conditions, such as wind and terrain.</p><p>Power output is a widely used and well-defined metric in cycling. For power based training <a href="https://www.trainingpeaks.com/blog/what-is-threshold-power/">Functional Threshold Power (FTP)</a>, the highest sustainable power output of a cyclist over a period of 60 minutes, is first determined. The power training routine then consists of periods in predefined ‘power zones’ that are based on a cyclist’s FTP. Cycling power is typically measured with <a href="https://www.slowtwitch.com/Tech/Power_Meter_101_3643.html">strain gauges at the crank</a>.</p><p>For running, however, there’s no agreed way to measure power output. Of course, it can be measured with <a href="https://www.researchgate.net/publication/13595989_Force_treadmill_for_measuring_vertical_and_horizontal_ground_reaction_forces">force plates on a treadmill</a>, but it’s not a viable option for running on a track. There are multiple techniques of measuring running power, one of which is <a href="https://www.stryd.com/">Stryd</a>, that estimates power using an accelerometer mounted on top of a foot. Their technology is proprietary, but there is a proposed model for power measurements, External Energy Summation Approach (EESA), that is described by <a href="http://www.georgeron.com/2017/12/stryd-running-power-model.html">Ron George</a>, and that seem to align well, with the results obtained from the Stryd power meter.</p><p>EESA is a comprehensive model that can approximate running power and how it changes over time, accounting for different conditions. Eventually, we would like to implement this model and perform such running power measurements, however, as a first exercise, we will only measure total work done (and hence average power) against external forces on a straight path with a much simpler model.</p><p>Hardware-wise we are using Arduino Nano IoT that will measure the acceleration and send it over Bluetooth Low Energy (BLE) to an Android smartphone.</p><h3>Accessing and sending the IMU data</h3><p>First, we need a way to record the acceleration. The Arduino Nano IoT has LSM6DS3 IMU (Inertial Measurement Unit) on board, providing acceleration and angular velocity via <a href="https://www.arduino.cc/en/Reference/ArduinoLSM6DS3">a library</a>. With the default output data rate of 104 Hz, we can poll the IMU for measurements every 10 milliseconds using this code</p><pre>#define IMU_POLLING_PERIOD 10<br>void setup() {<br>  ...<br>  if (!IMU.begin()) {<br>    Serial.println(&quot;Failed to initialize IMU!&quot;);<br>    while (true); // halt program<br>  }<br>  ...<br>}</pre><pre>void pollIMU() {<br>  float aX, aY, aZ;<br>  float gX, gY, gZ;<br>  unsigned long time;<br>  const char * spacer = &quot;, &quot;;</pre><pre>  if (<br>    IMU.accelerationAvailable()<br>    &amp;&amp; IMU.gyroscopeAvailable()<br>  ) {<br>    IMU.readAcceleration(aX, aY, aZ);<br>    IMU.readGyroscope(gX, gY, gZ);<br>    time = millis();</pre><pre>    reading = {<br>      .reading = {<br>        .time = time,<br>        .acceleration = {aX, aY, aZ},<br>        .gyroscope = {gX, gY, gZ}<br>      }<br>    };<br>    ...<br>  }<br>}</pre><pre>void loop() {<br>  ...<br>  if (currentMillis - lastMillis &gt;= IMU_POLLING_PERIOD) {<br>    lastMillis = currentMillis;<br>    pollIMU();<br>  }<br>  ...<br>}</pre><p>In this code we use the variable reading that is defined as follows</p><ul><li>Firstly, we define a structure to store three components of a vector.</li><li>Secondly, we define a structure to hold time of the reading (the internal clock is used), and two vectors for acceleration and angular velocity.</li><li>Finally, we build a union of this struct with a byte array of the same size (that is needed for serialisation before sending via Bluetooth), which is then filled in with actual data within pollIMU function.</li></ul><pre>typedef struct{<br>  float x;<br>  float y;<br>  float z;<br>} vector3d_struct_t;</pre><pre>typedef struct{<br>  unsigned long time;<br>  vector3d_struct_t acceleration;<br>  vector3d_struct_t gyroscope;<br>} imu_reading_struct_t;</pre><pre>typedef union{<br>  imu_reading_struct_t reading;<br>  uint8_t array[sizeof(imu_reading_struct_t)];<br>} imu_reading_t;</pre><pre>imu_reading_t reading = {};</pre><p>In order to collect the readings with the smartphone we will send the data over Bluetooth Low Energy (BLE) using the Arduino BLE library as follows:</p><ul><li>Define a BLE service (the UUID is arbitrary, and is used to filter for BLE devices that provide certain functionality)</li><li>Define a BLE characteristic. This can be thought of as a register, that can hold some value, and allows some actions to be performed by a central device (the smartphone in this case). For our purposes, we define a characteristic of size of our record, that can be read and subscribed for update notification.</li><li>Wait for a central device to connect, and update the characteristic value in pollIMU function while connection is maintained</li></ul><pre>BLEService powermetreService(&quot;1FFF&quot;);<br>BLECharacteristic imuReadingChar(&quot;2FFF&quot;, BLERead | BLENotify, sizeof(imu_reading_t));</pre><pre>void setup() {<br>  ...<br>  if (!BLE.begin()) {<br>    Serial.println(&quot;starting BLE failed!&quot;);<br>    while (true);<br>  }<br>  Serial.println(&quot;BLE started&quot;);<br>  BLE.setLocalName(&quot;Powermetre&quot;);<br>  BLE.setAdvertisedService(powermetreService);<br>  Serial.println(powermetreService.uuid());<br>  powermetreService.addCharacteristic(imuReadingChar);<br>  BLE.addService(powermetreService);<br>  imuReadingChar.writeValue(reading.array, sizeof(reading.array));<br>  BLE.advertise();<br>  Serial.println(&quot;BLE setup finished.&quot;);<br>}</pre><pre>void loop(){<br>  BLEDevice central = BLE.central(); // Wait for connection<br>  if(central) {<br>    Serial.print(&quot;Central device connected: &quot;);<br>    Serial.println(central.address());<br>    digitalWrite(LED_BUILTIN, HIGH);<br>    while(central.connected()) {<br>      long currentMillis = millis();<br>      if (currentMillis - lastMillis &gt;= IMU_POLLING_PERIOD) {<br>        lastMillis = currentMillis;<br>        pollIMU();<br>      }<br>    }<br>    digitalWrite(LED_BUILTIN, LOW);<br>  }<br>}</pre><p>The results can now be subscribed for, collected and stored with any BLE capable device. The full Arduino code and the accompanying Android app are available on <a href="https://github.com/fuzzylabs/wearable-my-foot/">Github</a>.</p><h3>Power analysis</h3><p>Even though we cannot perform measurements done by Stryd straight away, we can still approximate the work done from accelerometer data against external forces, with a few assumptions. Firstly, we assume that we are walking in a straight line; that way we only have to consider forces in one direction. And secondly, we assume that our speed is constant in the duration of a walk.</p><p>Work done for a straight path can simply be defined as an integral of a force <em>F </em>over displacement <em>s. F </em>in this case is a force vector in the direction of the walk (work done in two other orthogonal directions is assumed to be zero). By the second law, we know that <em>F=ma, </em>where <em>m </em>is a mass of a body, and <em>a</em> is an acceleration vector in the desired direction. For this experiment we simply measure out the path of 4.5 metres, mount the power metre on the chest, and walk trying to maintain speed. After the recording is done, we can analyse the results in a Jupyter Notebook.</p><h4>Removing gravity</h4><p>As a calibration step we estimate and subtract the gravity vector. Even though it is not strictly necessary if we know the exact direction we are walking at, as those vectors are supposed to be orthogonal, we only have the approximate direction (due to imprecise positioning of the sensor on the body).</p><p>To estimate it, we take a few seconds of standing still before walking when the only acceleration measured should be the gravity and take the mean average of that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*oWgm-930k9yE-1o8mrawgg.png" /></figure><pre>rps = 100 # records per second<br>_df = df.iloc[22*rps:25*rps] # hand-picked range<br>gravity_vector = _df.loc[:,[&quot;aX&quot;, &quot;aY&quot;, &quot;aZ&quot;]].mean()<br>display(ground_vector.values, np.sqrt((ground_vector**2).sum()))</pre><pre># array([ 0.93137248, -0.29392049,  0.2339799 ])<br># 1.0042860847765203</pre><p>The gravity has expected magnitude of ~1.0 (the Arduino’s IMU measures acceleration in <em>g</em>’s) and mainly points in the +X direction. Now we can subtract this from all the acceleration measurements to leave only the unbalanced forces acting on a body.</p><pre># Multiply by 9.8 to get acceleration in m/s^2<br>acceleration = (df.loc[:,[&quot;aX&quot;, &quot;aY&quot;, &quot;aZ&quot;]] - gravity_vector) * 9.8<br>acceleration[&quot;time&quot;] = df.time</pre><h4>Estimate work done</h4><p>With the resulting acceleration readings we can estimate how much work has been done. From here on we assume that the direction of the walk is -Z. Remembering our assumption of constant speed and known overall displacement, we calculate the work done and the average power as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*8fEhM3fBRePzimcAp6o7_g.png" /></figure><pre># Take only the records corresponding to the walk<br>rps = 100 # records per second<br>a, b = int(26 * rps), int(35.5 * rps)<br>sample = acceleration.iloc[a:b]<br>mass = 85<br>time = (sample.time - sample.time.min()) / 1000<br>dtime = (sample.time.max() - sample.time.min()) / 1000 # Total duration of a walk in seconds<br># Mean average speed.<br>vbar = 4.5 / dtime<br># Estimate displacement with the constant speed. <br>x = [x * vbar for x in time.values]<br># Integrate force with respect to displacement <br>work = sp.integrate.trapz(y=-sample.aZ.values * mass, x=x)<br>print(f&quot;Time: {dtime} s.\nSpeed: {vbar} m/s.\nAvg. power: {work / dtime} W.\nWork: {work} J.&quot;)</pre><pre># Time: 5.48 s.<br># Speed: 0.8211678832116788 m/s.<br># Avg. power: 20.991248881466902 W.<br># Work: 115.03204387043863 J.</pre><h4>Validating results</h4><p>To validate that our results are reasonable, we have also recorded acceleration with a built-in accelerometer of an Android phone. Straight away we can see that even though the exact values are different, the overall pattern is similar. The differences can be partially accounted for by the lower sampling rate of the Android accelerometre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*z1_pe6Y0JUHXUIRT4qaEwg.png" /></figure><p>Performing the same calculations on this data yields similar results with only about 1 Watt of difference.</p><pre>Time: 5.207 s.<br>Speed: 0.8642212406376033 m/s.<br>Avg. power: 19.814510206149293 W.<br>Work: 103.17415464341937 J.</pre><h3>Limitations</h3><p>Even though the estimate of work with the current approach is reasonable, there are multiple limitations that need to be addressed.</p><p>First of all, we try to position the sensor such that -Z axis aligns with the path, but it is not perfect. There does not seem to be an obvious solution to calibrate for walking direction in a similar way we calibrated for the direction of the gravity. This results in the work done being underestimated (since work done in two other orthogonal directions is not exactly zero).</p><p>Secondly, this model will not account for turning, as we only consider work to be done along single axis.</p><p>Both of this limitations can be mitigated if we employ the EESA model suggested by Ron George. However, it requires the instant velocity to be estimated from acceleration. Where we come to our third limitation, imprecise measurements. Trying to integrate acceleration over time we get increasing velocity, whereas we expect the velocity to come back to zero at the end of the walk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*UEWoDFwX3m9IY_YaA8N9vw.png" /></figure><p>For the same reason (lack of instant velocity measurements), we cannot estimate instant power in a way Stryd does it. Therefore, this needs to be considered as the most important issue, the solution for which is yet to be found (be it some signal processing required, or use of a different sensor).</p><p>This is an on-going project, and there more things to come, but for now, we encourage everyone interested to see the current implementation, and try it out for themselves, on <a href="https://github.com/fuzzylabs/wearable-my-foot/">Github</a>, that hosts the code for Arduino, Android app, and notebooks with analysis performed (along with some sample data).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685839604798" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzzylabsai/measuring-running-power-with-accelerometer-685839604798">Measuring Running Power with Accelerometer</a> was originally published in <a href="https://medium.com/fuzzylabsai">Fuzzy Labs Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Object Detection with OpenCV]]></title>
            <link>https://medium.com/fuzzylabsai/simple-object-detection-with-opencv-94f44369adcf?source=rss-8cf0f450e791------2</link>
            <guid isPermaLink="false">https://medium.com/p/94f44369adcf</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Misha Iakovlev]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 11:35:18 GMT</pubDate>
            <atom:updated>2020-07-31T07:33:36.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>Checkbox Detection with OpenCV</h3><p><em>The code is available on </em><a href="https://github.com/fuzzylabs/jupyter-delicacies/blob/master/vision/object-detection.ipynb"><em>GitHub</em></a></p><p>In <a href="https://fuzzylabs.ai/blog/the-battle-of-the-ocr-engines/">the previous post</a>, we have explored how texts can be detected and extracted, using different OCR methods. This time we will dive into how non-textual information can be extracted. Let’s say we are running a survey, that includes a printed questionnaire to be filled in with some multiple choice questions (i.e. it contains checkboxes with labels assigned to them). In order to perform any analysis on this survey, we need to extract the data from this survey digitally. We do not want to record the results of a large number of questionnaires manually, as this is a laborious task. Hence, we need a way to detect those checkboxes automatically, so the forms can be processed in bulk.</p><p>For this task, we will be using <a href="https://opencv.org/">OpenCV</a>, a computer vision library, that provides a wide range of methods for image manipulation and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*HnyfnJ2ihJtnfWBikblwgQ.png" /><figcaption>The original segment of a form for analysis</figcaption></figure><p>What are we working with? We have a section of the form that contains multiple checkboxes with the associated labels. Additionally, we have some artefacts (i.e. one of the labels crossed out with a thick line, and a hand-drawn circle in the corner) that might make our lives harder. For the purpose of the exercise, our task will be to correctly identify the locations and dimensions of the checkboxes present.</p><h3>Image Preparation</h3><p>Before we proceed with detection, we first want to try to separate our objects of interest (i.e. checkboxes) from the background, and, if possible, from other objects on the scene.</p><h4>Thresholding</h4><p>There exist multiple methods that can be used for preparing the image for the downstream task of object detection, the very simplest of which is thresholding.</p><p><strong><em>Thresholding: </em></strong>an operation that turns an image into a binary one, where pixels with intensity level above a certain threshold are turned white, and all the rest of the image is turned black. <a href="https://en.wikipedia.org/wiki/Otsu&#39;s_method">Otsu’s method</a> is used to determine an appropriate threshold automatically, using the distribution of intensity values.</p><pre>_, img_bin = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)<br>img_bin = 255 - img_bin</pre><p>The thresholded image is inverted since OpenCV considers white areas as “objects” and black areas as “background”, which is important for the downstream task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*FkhawgWxNiRIL6rhLKpsaw.png" /><figcaption>Thresholded image</figcaption></figure><p>The image is now ready for further manipulations, with the relevant objects highlighted and any potential background noise removed. But can we do better?</p><h4>Opening</h4><p>The thresholded image still contains some elements that are not needed for our task. We are only interested in vertical and horizontal lines that make up checkboxes, and, therefore, would like to get rid of text labels and any small artifacts that might be present on a page. We can attempt removing these elements using opening.</p><p><strong><em>Opening: </em></strong>a morphological operation that removes everything that does not fit a structural element of certain dimensions. It is a compound operation that consists of the successive application of dilation and erosion.</p><p>We cannot find a structural element (sometimes called kernel), that would separate the boxes from the other object, for this image. However, we can do this in two steps: extracting vertical and horizontal components of the boxes separately, applying opening with vertically aligned and horizontally aligned rectangular kernels respectively. The resulting openings can then be combined together.</p><pre>vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,15))<br>vertical = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel, iterations=1)</pre><pre>horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1))<br>horizontal = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel, iterations=1)</pre><pre>img_opened = cv2.addWeighted(vertical, 0.5, horizontal, 0.5, 0.0)<br>_, img_opened = cv2.threshold(img_opened, 0, 255, cv2.THRESH_BINARY)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oczKf56KfZHQGIPt9q1WHg.png" /><figcaption>Results of opening applied to the thresholded image</figcaption></figure><h4>Edge Detection</h4><p>Alternatively, as we are only interested in the locations of the checkboxes and they have a sharp contrast with the background, to separate them out we can perform edge detection.</p><p><strong><em>Edge detection: </em></strong>an operation that identifies locations of the image with a rapid change in intensity values. Here, we are specifically using the <a href="https://en.wikipedia.org/wiki/Canny_edge_detector">Canny edge detector</a>. The specifics of the algorithm are not essential for the article, but it is worth noting that Canny detector, in comparison to some other simpler detectors, applies additional noise filtering and removes candidate edges that are too small or shallow (i.e. might be image artefacts)</p><pre>CANNY_KERNEL_SIZE = 100<br>img_canny = cv2.Canny(img, CANNY_KERNEL_SIZE, CANNY_KERNEL_SIZE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*VTHHq03NBBTWj9Ya83HEQQ.png" /><figcaption>Results of edge detection</figcaption></figure><h3>Contours</h3><p>Having the image prepared, we next extract the contours (a set of points that define an entity) of every object on the scene (i.e. every ‘blob’ of white pixels present on the image).</p><pre>def get_contours(img_bin):<br>    contours, _ = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br>    return contours</pre><p>We only keep the top level or external contours and plot them over the original image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Tw91uh_K5EexbIuF5ixKcA.png" /><figcaption>Contours for the objects after each preparation method</figcaption></figure><p>The good thing is that all checkboxes are detected, the bad thing, however, is that we still have plenty of unwanted objects. Therefore, we need to perform filtering to only include the contours for the objects of interest.</p><h3>Contour Filtering</h3><h4>By Area</h4><p>We know that our boxes are roughly 25 by 25 pixels, and hence have an area of roughly 625 pixels squared. Therefore, we can try to filter out all the contours which area is too small or too large with the following code.</p><pre>def is_correct_area(contour, expected_area=625, tolerance=200):<br>    area = cv2.contourArea(contour)<br>    return abs(area - expected_area) &lt;= tolerance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Qg5YZqTfkIjRZFMJDdNAQQ.png" /><figcaption>Contours after filtering for area</figcaption></figure><p>For all pre-processed images, this filter removes the contours of the text labels. But the crossed-out text’s and the circle’s contours are still present on the images with the simple thresholding and edge detection. So, this method is not robust enough for our purpose. It is worth noting, though, that this is not a problem for the image with the opening: the circle was broken down into smaller pieces enough to be filtered out with this method.</p><h4>By Bounding Box</h4><p>The previous results can be improved if we add the information on shapes. We can get bounding boxes (i.e. a minimal box that encloses a given contour) and filter out ones that do not have square dimensions.</p><pre>def are_bounding_dimensions_correct(contour, expected_area=625, tolerance=200, squareness_tolerance=5):<br>    area = cv2.contourArea(contour)<br>    x, y, w, h = cv2.boundingRect(contour)<br>    return abs(area - expected_area) &lt;= tolerance and abs(w - h) &lt;= squareness_tolerance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*-nFQVXBgdqySuorE656ifQ.png" /><figcaption>Contours after filtering for bounding box aspect ratio</figcaption></figure><p>This filter successfully removes the unwanted thick line, but the circle is still present, as its bounding box has a roughly square shape.</p><h4>By Contour Matching</h4><p>To combat that, we can compare contours directly instead of relying on their bounding boxes. We can define a template box of square shape, and filter out all the contours that do not match the template or do not match the area requirement (we still have to check if sizes are correct).</p><pre>def is_contour_square(contour, contour_tolerance=0.0015, square_side=25, area_tolerance=200):<br>    expected_area = square_side * square_side<br>    area = cv2.contourArea(contour)<br>    template = np.array([[[0, 0]], [[0, 1]], [[1, 1]], [[1, 0]]], dtype=np.int32)<br>    return cv2.matchShapes(template, contour, 1, 0.0) &lt;= contour_tolerance and abs(area - expected_area) &lt;= area_tolerance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*3x143vS_ju2T06YsPjJqPw.png" /><figcaption>Contours after filtering for contour shape</figcaption></figure><p>Doing that, allows us to identify the shapes that closely match our desired template, and therefore filter out the unwanted objects, including the hand-drawn circle.</p><h3>Bottom line</h3><p>Having multiple methods of pre-processing and contour filtering tested, we can conclude that the combination of opening (since it removes most of the unwanted elements all by itself) and contour matching (since it provides high precision of filtering) works best for our task. The great thing is that a similar approach can be further extended to account for other elements that can be encountered in forms, simply by defining appropriate kernels and templates.</p><p>Of course, these exact methods are not applicable to every single problem that can be found in the real world, and some additional processing might be required: such as colour masking instead of thresholding, or denoising of the image as a pre-processing. Hence, the reader is encouraged to play around with <a href="https://github.com/fuzzylabs/jupyter-delicacies/blob/object-detection/vision/object-detection.ipynb">the code provided</a>, apply it to other problems and try to adapt it to suit their needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94f44369adcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzzylabsai/simple-object-detection-with-opencv-94f44369adcf">Simple Object Detection with OpenCV</a> was originally published in <a href="https://medium.com/fuzzylabsai">Fuzzy Labs Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Battle of the OCR Engines — Tesseract vs Google]]></title>
            <link>https://medium.com/fuzzylabsai/the-battle-of-the-ocr-engines-tesseract-vs-google-902c302e71a1?source=rss-8cf0f450e791------2</link>
            <guid isPermaLink="false">https://medium.com/p/902c302e71a1</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[optical-character-recogn]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Misha Iakovlev]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 13:40:57 GMT</pubDate>
            <atom:updated>2020-07-28T12:01:52.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Battle of the OCR Engines — Tesseract vs Google Vision</h3><p><em>The code is available on </em><a href="https://github.com/fuzzylabs/jupyter-delicacies/blob/master/vision/ocr.ipynb"><em>GitHub</em></a></p><p>Let’s say you want to extract some information from paper prescriptions (to perform some trend analysis afterwards, or to simply check if the prescription is valid against a database; the exact reasons may vary and are not too important here). You could type them into a computer database manually and call it a day. But it gets tedious if the number of those to type in becomes large, and the time is precious. This is when Optical Character Recognition (OCR) techniques may come in handy.</p><p>OCR is an umbrella term encompassing a range of different technologies that detect, extract and recognise text from images. There exist a multitude of approaches for OCR from very simple ones, that can only recognise clear text in a specific font, to particularly advanced, that employ machine learning and can work with both printed and handwritten texts in multiple languages. We are going to focus our attention on two specific ones here.</p><h3>What are our options?</h3><p>In this article we are going with two specific OCR tools: <a href="https://github.com/tesseract-ocr/tesseract">Tesseract OCR</a> and <a href="https://cloud.google.com/vision/">Google Cloud’s Vision API</a></p><p>Tesseract OCR is an offline tool, which provides some options it can be run with. The one that makes the most difference in the example problems we have here is page segmentation mode. In many cases, one might resort to run it in auto-mode, but it’s always useful to think about what the potential layouts of the documents might be and hence provide some hints to Tesseract, so it can yield more accurate results. For simplicity, I will not cover all of the modes available, but experiment with three, that, at least intuitively, might fit the layouts of the documents we are working with here:</p><ul><li>Single Block: the system assumes that there is a single block of text on the image</li><li>Sparse Text: the system tries to extract as much text as possible, disregarding its location and order</li><li>Single Column: the system assumes that there’s a single column of lines of texts</li></ul><p>Google Vision, on the other hand, does not provide as much control over its configuration as Tesseract. However, its defaults are very effective in general. There are two distinct OCR models that are worth experimenting with:</p><ul><li>Text Detection model: detects and recognises all text on a provided image</li><li>Document Text Detection model: practically performs the same task, but is tuned to better suit dense texts and documents</li></ul><h3>Into the first example</h3><p><em>N.B. the full recognised text results are not provided here, for the sake of keeping the article readable. However, the reader is encouraged to play around with </em><a href="https://github.com/fuzzylabs/jupyter-delicacies/blob/master/vision/ocr.ipynb"><em>the notebook</em></a><em> provided and see full results for themselves.</em></p><p>Starting with our first example: a scanned prescription for amoxicillin (kind of antibiotic). We will first look at how the methods described above handle this form as is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*YYmQ_VPoGpzveXOudJvEUw.png" /><figcaption>Original source: <a href="https://bnf.nice.org.uk/guidance/prescription-writing.html">https://bnf.nice.org.uk/guidance/prescription-writing.html</a></figcaption></figure><p>A couple of observations to make here:</p><ul><li>Both Single Block and Single Column Tesseract modes detect some spurious boxes as text (we may assume that the text is not dense enough for these modes)</li><li>Both Google models detect the text on the watermarks, that is not relevant to our task</li></ul><p>I will not be talking about the accuracy of the recognition yet, since there’s a way to improve the detection first!</p><h3><strong>Does image pre-processing help?</strong></h3><p>There’s, of course, a plethora of ways that images can be pre-processed before analysis, including but not limited to different ways of filtering and de-noising, lightning adjustments, sharpening, you name it. But here we don’t have to do anything too convoluted to remove the background. We can perform thresholding, an operation that turns an image into a binary one by setting the pixels to black if their intensity values are above a certain threshold, and to white otherwise. Conveniently, the OpenCV library provides a method to threshold the image. Instead of picking and hard-coding some specific threshold <a href="https://en.wikipedia.org/wiki/Otsu&#39;s_method">Otsu method</a> can be used, which chooses the best threshold, based on the distribution of pixel intensities. The results after thresholding already look more promising. Let’s investigate what we see here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*otC5I7Cdu0FfoIhExiit3Q.png" /></figure><ul><li>Tesseract’s results haven’t changed much (since it was not affected by the background anyway).</li><li>However, Google’s results have definitely improved: no more unwanted elements are recognised.</li><li>Tesseract’s Sparse Text mode still stands superior to the other two, detecting the layout correctly, and recognising most of the text without mistakes. There are some occasional extra characters inserted: for example “i 50 Stanhope Street”, where ‘i’ is not a real character, but part of the box to the left of the text.</li><li>Google Document Text Detection model does not seem to perform well on this one, combining texts into a single paragraph when they clearly do not belong together. The possible reason here is that the text is not dense enough for that particular model.</li><li>We can also see one of the weak sides of Google Vision: it sometimes fails to recognise short strings or lone characters standing on their own (Google Text Detection model failed to detect that single ‘5’ in the middle of the page). But overall, when the text was detected, it was indeed recognised correctly.</li></ul><p>So, as you can see, there’s no one-size-fits-all model. In this particular case, after the experiment, I would go with either Tesseract Sparse Text mode or Google Text Detection model (leaning more towards the former, as the 5 and other single-digit numbers that may come in the following documents, that Google misses, might be quite important for the task), with the thresholding as the preprocessing step.</p><h3>What about a different layout</h3><p>To illustrate that the nature of a document might influence the choice of a model, let’s go through another example. Here we have a receipt from a hotel, that was submitted to claim reimbursement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*3-DYfWImevUhyUcXTdWwpw.png" /><figcaption>Original source: <a href="https://www.imperial.ac.uk/staff-travel-and-expenses/whilst-you-are-travelling/obtaining-receipts-to-evidence-expenditure/receipt-examples/">https://www.imperial.ac.uk/staff-travel-and-expenses/whilst-you-are-travelling/obtaining-receipts-to-evidence-expenditure/receipt-examples/</a></figcaption></figure><ul><li>All three modes of Tesseract did a good job detecting the text on the image. However, Single Block and Column modes kept the lines of the text intact, which is convenient if you wants to match label-value pairs in the analysis afterwards.</li><li>Tesseract’s recognition, on the other hand, is far from perfect (e.g. “MTE: Jin, 26,16 TIE: 03:4” instead of “DATE: Jun, 26, 16 TIME: 09:47”). My guess would be that it is due to a narrow font and the image quality not being the sharpest. Some pre-processing steps to improve edges of the letters might yield better results, but this is just a speculation, since this was not tested.</li><li>In comparison, Google Vision recognises all the text with almost no errors, including the handwritten “Housing” (which Tesseract recognised as “‘stﬂrg”)</li><li>The segmentation by the Text Detection model was again better in comparison to the Document Text Detection model, even though it breaks up some of the lines of text</li></ul><p>At this point, I’d like to add a note on matching label-value pairs. Tesseract’s Single Column mode conveniently provides lines of the receipt, so the label-value pairs can be parsed trivially. However, if this was not the case (and it isn’t for the results of Google Vision), the pairs can still be matched if needed by using the coordinates of the detected text, which are provided by both Tesseract and Google.</p><p>In conclusion, even though Tesseract Single Column provides a nice layout, I would choose Google Vision for this task, as it provides much better accuracy of recognition (including the handwritten part, which is important for this particular example).</p><h3>Take-home message</h3><p>In this short blog post, we’ve compared how Tesseract OCR and Google Vision perform on two specific tasks, but this is by no means an exhaustive overview. When employing OCR, you need to consider the nature of the images you are working with, and experiment with different OCR models to find one that is the most suitable for their application. Additionally, the real-world data might not be as clean as the examples above, therefore some pre-processing steps might be required for recognition to be successful. And finally, even though this step is out of the scope of this post, it is worth mentioning, that after the recognition some post-processing might be required, such as removal of the extra characters, or spell-checking (it depends on what the further analysis is).</p><p><a href="https://github.com/fuzzylabs/jupyter-delicacies/blob/master/vision/ocr.ipynb">The notebook</a> with the code producing the results for the examples in this post is available. The readers are highly encouraged to give it a try and experiment with their sample data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902c302e71a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzzylabsai/the-battle-of-the-ocr-engines-tesseract-vs-google-902c302e71a1">The Battle of the OCR Engines — Tesseract vs Google</a> was originally published in <a href="https://medium.com/fuzzylabsai">Fuzzy Labs Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>