<?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 Vignesh Ungrapalli on Medium]]></title>
        <description><![CDATA[Stories by Vignesh Ungrapalli on Medium]]></description>
        <link>https://medium.com/@hawking23?source=rss-a83b80da731f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JCHvFAWhliUJibqbVqWVSA.jpeg</url>
            <title>Stories by Vignesh Ungrapalli on Medium</title>
            <link>https://medium.com/@hawking23?source=rss-a83b80da731f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:14:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hawking23/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[Features — Harris Corners]]></title>
            <link>https://medium.com/buzzrobot/features-harris-corners-8d972b1b4faa?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d972b1b4faa</guid>
            <category><![CDATA[tracking]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Sun, 18 Nov 2018 11:56:10 GMT</pubDate>
            <atom:updated>2018-11-24T06:07:21.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Features — Harris Corners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ixyV7pPxDassqvZz404esg.png" /><figcaption>Fig. 0: Image captured from two different views [0]</figcaption></figure><p>Given the images in Fig.0, and tasked with the problem of stitching them together to form a panoramic view, what would be the first thing you would think of doing. Well, I would try to find similarities between these images, more concretely find points in one image which appear in the other. These points are called correspondences/feature keypoints/Interest Points. This blog is about one of the fundamental algorithms used to <strong>detect</strong> such Interest Points — The Harris Corner detector.</p><p>Before we dwell into Harris Corner detector, we will first understand some terms/concepts regarding Features.</p><p><strong>Feature Keypoint</strong>: As described above, these are points of interest in image which will help us uniquely identify the small area surrounding them in another image (note, another image here could be a different view of the image, could be consecutive frames in a video etc.).</p><p><strong>Feature Descriptor</strong>: Say we have identified the feature keypoints. Now we need a representation to describe them (think something like a hash but not exactly that) so that this representation can be used in the process of matching/finding this feature in a different image.</p><p>So, what makes for a good feature? The identified features must have following properties:</p><ol><li>Repeatability/Precision: The feature should be such that it can be found in several images despite certain geometric/photometric transformations.</li><li>Salient: Should be unique to a good degree and should be distinctive. Any point which is not distinctive is hard to be matched.</li><li>Compactness: We have thousands/lakhs of pixels but we would want the number of features to be a few thousands for sake of efficiency</li><li>Locality: Remember we are looking at local features (as against global image features like image histogram). Features should be described by their small neighborhoods.</li></ol><p>Corners are interest points which satisfy some of the above properties. They also help solve another problem called the Aperture problem. Given a region in the image with just Edge or flat region it is impossible to identify it uniquely. There could be multiple matching patches to this given patch. There is also manifestation of this problem in case of motion. Given a small window, and only an edge, the motion along the edge (perpendicular to the gradient direction) is ambiguous. You might feel the edge is moving upwards where in reality it could be moving downwards and side wards. A Corner solves this problem.</p><h4>Harris Corners</h4><p>The idea behind Harris Corners is that for a flat region there is almost zero change (gradient), for a region with Edge there is change only along the direction of gradient and no change along the Edge but for a Corner there is significant change in all directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI6OMgks7DX-FkYBsbKemQ.png" /><figcaption>Fig. 1: <strong>Leftmost</strong>: Flat Region has no change. <strong>Center</strong>: No change along the Edge. <strong>Rightmost</strong>: Significant change even on small movements. [1]</figcaption></figure><p>Consider a window on the image. Now move the window by a small amount and compute the difference between these two positions (Fig. 1). You can see that for region with Corner there is significant change (the difference).</p><p>Putting it formally,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*JIIok4RLSd2QhzR5.png" /><figcaption>Eq. 0</figcaption></figure><p><em>(x,y)</em> is the window in the image which is under consideration. <em>(u,v)</em> denote moving the window in ‘x’ direction by <em>u</em> amount and in the ‘y’ direction by <em>v</em> amount. <em>E(u, v) </em>is a weighted (by <em>w(x), </em>normally a gaussian) Sum of Squared Difference(SSD) between Image pixel values captured by window which moved <em>(u, v)</em> distance from its initial position. As an implementation detail, SSD is calculated every pixel. Another point to note is that this SSD here is equivalent(not equal) to the Auto Correlation of the Image (You can treat proving this as an exercise. [1] has an explanation in case you are unable to figure out).</p><p>Coming back to Eq. 0, We have this uncomfortable looking <em>I(x+u, y+v)</em> term. Well, worry not. We have Taylor Expansion for the rescue. We will create Taylor expansion approximation for <em>I(x+u, y+v)</em>. As a refresher, given an infinitely differentiable function f(x),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*sZviYLnxcOr4dpQc.png" /><figcaption>Eq. 1</figcaption></figure><p>(u, v) are in the fairly small neighborhood and hence can be used in above. Note that the above can also be arrived at using finite differences for derivatives.</p><p>Eq. 1 represents a function with one variable but we have a function with two variables. The approximation would look as in Eq.2;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*dP4GVz67dwpVoWJo.png" /><figcaption>Eq. 2</figcaption></figure><p>I_x -&gt; Image gradient along x.</p><p>I_y -&gt; Image gradient along y.</p><p>Substituting value of <em>I(x+u, y+v)</em> from Eq.2 into Eq. 0 will lead to following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*fu8vHQKbIeeRYjzW.png" /><figcaption>Eq. 3</figcaption></figure><p>Now, the summation is over <em>(x, y)</em> so let us take out other constants from inside the summation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*OqObyXgaqDyRqZCj.png" /><figcaption>Eq. 4</figcaption></figure><p><strong>Eigenvalue analysis</strong>:</p><p>Note that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*8yX0ZmmZYPD5RAY2.png" /><figcaption>Eq. 5</figcaption></figure><p>Fig. 2 shows a map of R and eigenvalues and their implications on the region being flat, edge or a corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*oHLf_GzueXHMJfqolG_HQw.png" /><figcaption>Fig. 2: Eigenvalue of M and its implication [1]</figcaption></figure><h4>Implementation Details</h4><ol><li>Compute the Image derivatives along the horizontal and vertical direction. This is done by computing derivative of a gaussian followed by convolution (gaussian for smoothing and thanks to associative property of convolution).</li><li>Compute the Outer products of the above gradients (I_x with I_x, I_x with I_y and I_y with I_y)</li><li>Convolve gaussian (remember <em>w(x)</em>?) with each of the above outer products to get the Moment matrix <em>M</em>. A minor detail, <em>M</em>, in Eq. 4 is a summation which is here dubbed as a discrete convolution over the outer products of gradients.</li><li>Compute <em>R</em> to find the kind of region</li><li>There is one last step which is not discussed above: Non-maximal suppression. In a small region, compute local maximum and report it as corner while suppressing the other values in the region. This reduces the number of noisy points.</li></ol><p><strong>In the End…:</strong></p><p>There are other algorithms which interpret/analyze “<em>R</em>”in a different way . One example of this is [4]. Harris Corners is one of the fundamental algorithms for features. Note that this gives us just the keypoints and not descriptors (remember? we need descriptors to do something useful like matching). Also Harris Corners is not Scale Invariant (more about this next). We will look at some Scale Invariant (and lot of other “invariant”ness) algorithms in the upcoming articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*aEdVWWC5BMSaxTQZ.png" /><figcaption>Fig. 3: Sample output of running Harris Corners [5]</figcaption></figure><h4>References</h4><p>[0] : <a href="http://szeliski.org/Book">Computer Vision: Algorithms and Applications</a>, Richard Szeliski</p><p>[1]: <a href="https://www.youtube.com/watch?v=_qgKQGsuKeQ&amp;list=PLd3hlSJsX_Imk_BPmB_H3AQjFKZS9XgZm&amp;index=5">UCF CRCV 2012</a></p><p>[2]: <a href="https://in.udacity.com/course/introduction-to-computer-vision--ud810">GATech/Udacity Computer Vision</a></p><p>[3]: <a href="http://www.bmva.org/bmvc/1988/avc-88-023.pdf">A Combined Corner and Edge Detector</a></p><p>[4]: <a href="http://www.ai.mit.edu/courses/6.891/handouts/shi94good.pdf">Good Features to track</a></p><p>[5]: <a href="https://en.wikipedia.org/wiki/Chessboard_detection">https://en.wikipedia.org/wiki/Chessboard_detection</a></p><p>[6] <a href="http://latex2png.com/">http://latex2png.com</a> -&gt; For math used in the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d972b1b4faa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/buzzrobot/features-harris-corners-8d972b1b4faa">Features — Harris Corners</a> was originally published in <a href="https://medium.com/buzzrobot">BuzzRobot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal Style Transfer]]></title>
            <link>https://medium.com/data-science/universal-style-transfer-b26ba6760040?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b26ba6760040</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 19:02:24 GMT</pubDate>
            <atom:updated>2017-12-24T07:43:38.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*YJ3ktQnzMdeyUkKURwPY6w.png" /><figcaption>Fig. 0</figcaption></figure><p>One of the interesting papers at NIPS 2017 was this: <a href="http://arxiv.org/abs/1705.08086">Universal Style Transfer via Feature Transform</a>[0]. There are a bunch of Neural Network based Style Transfer techniques especially after <a href="http://arxiv.org/abs/1508.06576">A Neural Algorithm of Artistic Style</a>[1]. All the existing techniques had one of the following major problems:</p><ol><li>Not efficient during Inference: An example of this is the [1] mentioned above.</li><li>Style Specific Networks. An example of this is the paper <a href="http://arxiv.org/abs/1603.08155">Perceptual Losses for Real -Time Style Transfer and Super-Resolution</a>[2].</li><li>Poor generalizing abilities in terms of output quality: An example of this is the paper <a href="https://arxiv.org/pdf/1703.06868.pdf">Arbitrary Style Transfer in Real-Time with Instance Normalization</a>[3]</li></ol><p>The paper under discussion claims to solve the above problems. This blog is a commentary on the paper. Assumes some basic understanding of Deep Learning and Linear Algebra. The repository for code by the authors can be found <a href="https://github.com/Yijunmaverick/UniversalStyleTransfer">here</a>.</p><p>At places (Fig.9, 10 and 12) I have used images to represent math. This is mostly due to crappy math support by medium . I used <a href="https://latexbase.com/">https://latexbase.com/</a> for generating math on latex and later taking their snapshot. (I know, very painful)</p><p><strong>The Problem</strong> (in case it is not already clear from above): Given an image with certain content in it(call it Content Image) and another image with certain style embedded in it (think of an image of a famous painting. Lets call this Style Image). The Goal is to build a new Image which has the contents of the Content Image and Style of the Style Image. Something as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t73dy_3LOwvTRzgpA_QMiA.png" /><figcaption>Fig. 1 Content Image + Style Image = Stylized Content Image [4]</figcaption></figure><p>The selling point of this paper is that it is “learning-free”. Existing feed-forward based techniques would need to be trained on pre-defined styles and then fine tuned for new styles. Whereas, this paper presents a method which is completely independent of the style during train phase making it a “learning-free” approach. Note that [3] is something closer in essence to this paper but relies on style images at training time (but can generalize well for arbitrary style images).</p><p>The style transfer problem, in this paper, is formulated as a combination of two processes, viz., Image Reconstruction and Feature transform using Whitening and Color Transform(WCT).</p><h4>Image Reconstruction</h4><p>A classic Encoder-Decoder mechanism is the one where in a image is fed into an Encoder network which Encodes the image forming a representation and passed on to a decoder which tries to reconstruct the original input image. The paper uses a slight modification of this for image reconstruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*kUN6tzFXIKWupcKkh3gWnA.png" /><figcaption>Fig. 2 A classic Encoder-Decoder Network(just a reference not used in paper) [5]</figcaption></figure><p>As a first step they train VGG-19(called VGG from here on) on Imagenet Image classification task. This is used as the Encoder. As a next step, the Encoder is fixed and the decoder is trained to reconstruct the Image. Looks as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*ybzfpSxRJzS6hV3fjgTlPQ.png" /><figcaption>Fig. 3 Encoder-Decoder for reconstruction [0]</figcaption></figure><p>Some clarity on the Relu_X_1 and the DecoderX that you see in the above Image: They train more than one decoder for reconstruction. In fact, they train 5 decoders for reconstruction. We will soon see the reason. But, ‘X’, here refers to the layer number in VGG network. X = 1,2,3,4,5 are the values used in the paper. The VGG encoder part ends at layer Relu_X_1 and the decoder(DecoderX) is constructed symmetric to this encoder. They use a combination of pixel reconstruction loss and feature loss as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*jogCKrZT2miylLzuRCWsPw.png" /><figcaption>Fig.4 Loss function for Decoder Reconstruction</figcaption></figure><p>Pixel reconstruction is a simple L2 norm of the reconstructed output(I_o) and the input image(I_i). Feature loss is the L2 norm of the Relu_X_1 features of the reconstructed output and input image. Here Φ represents the VGG-19 encoder that extracts Relu_X_1 features. λ is the weighing factor for the losses. The Encoder and the Decoder are now trained and fixed. Notice that we never used any style image in the whole process of training.</p><h4>Stylization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*o9GPjGpyfQp2vYmff8gjyw.png" /><figcaption>Fig. 5 Single level Stylization [0]</figcaption></figure><p>The above image represents single level stylization. This includes the Content Image (C) and style Image (S) as input to the Encoder (VGG Relu_X_1). Note that these inputs are passed in independent of each other (Each goes through the VGG independently). The output of the Encoder is sent into the Whitening and Coloring Transform block (we will see this in more detail in the next section) whose output is then passed on to the decoder (Recons DecoderX) to get the final stylized output. The image below shows the stylized output for X=1,2,3,4 and 5. The lower layers (1 etc.) capture features like style color whereas higher layers(say, 5) captures style structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*4t6A3cwJ3Mz4A_h4lCdIoA.png" /><figcaption>Fig.6 Stylized outputs for each of the layers/decoders [0]</figcaption></figure><p>The authors proceeded to use the feature from all layers instead of sticking to just one. That results in an architecture as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*urbx5J1WFhjA9jcYCqnIBg.png" /><figcaption>Fig. 7 Multi level stylization [0]</figcaption></figure><p>We start off with Content and Style Images feeding them to VGG and Relu_5_1 feature is extracted and sent into WCT and then Decoder5. The output of Decoder5 is fed into VGG along with the style image and Relu_4_1 is extracted and the process continues until we get output from Decoder1. The image below shows results from such a multi level inference. I_5 is effectively the output of first level (in above image) and I_1 is the output of Decoder1(the final output). Definitely looks better than single level stylization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*3YhbfNtWb_0nATF-IcIHUA.png" /><figcaption>Fig. 8 Multi level stylization outputs at various levels [0]</figcaption></figure><h4>Whitening and Color Transform(WCT)</h4><p>In the previous section we treated WCT as a black-box. Let us dig a bit into this to understand what exactly it is doing. Remember that we never used any style image during model training. Our encoder is a Imagenet trained VGG and the decoders are trained for reconstruction at varies feature levels of the Encoder (Relu_<strong>X</strong>_1). WCT does some cool math which plays a central role in transferring the style characteristics from style image while still preserving the content.</p><p>Let us look at WCT as process of disassociating the current style of the input image and associating the style of the style image with the input image. The first step is whitening.</p><p>We know that input to the WCT block is the output of the Encoder block (Relu_X_1). Relu_X_1 has shape of <em>C x H x W</em>, where <em>C</em> is the number of channels, <em>H </em>is the height and <em>W </em>is the width of a feature map. This is assuming a single input image. We vectorize these feature maps such that we have <em>C</em> vectors of length <em>H x W</em>. Let <em>f_c</em> be the vectorized feature map of shape [<em>C , (H_c x W_c)], </em>where <em>H_c</em> and <em>W_c</em> are respectively the height and width of the feature maps at certain Relu_X_1 due to content image . Similarly, let<em> f_s</em> be the vectorized feature map of shape [<em>C, (H_s x W_s)</em>], where <em>H_s</em> and <em>W_s</em> are respectively the height and width of the feature maps at certain Relu_X_1 due to style image.</p><p><strong>Whitening Transform:</strong></p><p>Our goal is to find a transformation of <em>f_c, </em>let us call it<em> f_ct </em>such that the co-variance matrix of <em>f_ct </em>is an Identity matrix, i.e., <em>f_ct x (f_ct.transpose)= I. </em>This ensures that the feature maps have no correlation. More formally,</p><p><em>f_ct = W x f_c , </em>where W is a transformation matrix. A very common choice of W is inverse square root of Y, where Y is the co-variance matrix <em>f_c x (f_c.transpose). </em>In a better representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*2IcRiHbYRFutFheiFstFGQ.png" /><figcaption>Fig. 9</figcaption></figure><p>A minor note: Going by the definition of co-variance matrix, to have <em>Y =</em> <em>f_c x (f_c.transpose)</em> we will need that the mean value m_c (per channel mean) be subtracted from <em>f_c</em>. <em>f_c</em> above actually represents the value after subtraction.</p><p>You can see that <em>Y</em> is a symmetric matrix with real values. So we can have an eigen decomposition of this matrix and our final <em>f_ct</em> looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*kwnyj2t_-RMWBY9t8Mn47Q.png" /><figcaption>Fig. 10</figcaption></figure><p>It is easy to verify that the Co-variance matrix of the new <em>f_ct</em> is an Identity matrix (uncorrelated features). You can treat this as an exercise :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*pYfBjqgY06TLVtyCiiBhbg.png" /><figcaption>Fig. 11 Inverting whitened Relu_4_1 features [0]</figcaption></figure><p>The above is an experimental validation of the whitening process. Basically, they run the model with just the whitening block (no coloring block). You can see that the final construction preserved the content (golden gate) but removed any information related to style.</p><p><strong>Coloring Transform:</strong></p><p>This is kind of an inverse operation of the Whitening Transform. Remember that by whitening we effectively dis-associated the features off their styles. Now we will associate to these the style of the style Image by transforming the whitened result (equation 1).</p><p>Our goal is to find a transform of <em>f_ct</em>, let us call it <em>f_cst</em> such that the co-variance matrix of <em>f_cst</em> is equal to the co-variance matrix of <em>f_s</em>. Remember that <em>f_s</em> is the vectorized feature map due to style image. A minor note again, mean <em>m_s</em> is subtracted from <em>f_s</em> (same reason as mentioned above). More formally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*XtW7aqQfu5siIIpv7vsILQ.png" /><figcaption>Fig. 12</figcaption></figure><p>It is easy to verify (2) with value of <em>f_cst</em> as above (again, exercise :))</p><p>I have tried to explain in brief the gist of the paper. If you find it interesting go ahead and read the paper [0] . The paper has much more details on the training and other features like User Control and Texture synthesis. You can also try out the code here: [6]</p><p>If you liked the article go ahead, join your hands and give some 👏 :)</p><p><strong>References</strong>:</p><p>[0]: <a href="http://arxiv.org/abs/1705.08086">Universal Style Transfer via Feature Transform</a></p><p>[1]: <a href="http://arxiv.org/abs/1508.06576">A Neural Algorithm of Artistic Style</a></p><p>[2]: <a href="http://arxiv.org/abs/1603.08155">Perceptual Losses for Real -Time Style Transfer and Super-Resolution</a></p><p>[3]: <a href="https://arxiv.org/pdf/1703.06868.pdf">Arbitrary Style Transfer in Real-Time with Instance Normalization</a></p><p>[4]: <a href="https://research.googleblog.com/2016/02/exploring-intersection-of-art-and.html">https://research.googleblog.com/2016/02/exploring-intersection-of-art-and.html</a></p><p>[5]: <a href="https://nsarafianos.github.io/icip16">https://nsarafianos.github.io/icip16</a></p><p>[6]: <a href="https://github.com/Yijunmaverick/UniversalStyleTransfer">https://github.com/Yijunmaverick/UniversalStyleTransfer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b26ba6760040" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/universal-style-transfer-b26ba6760040">Universal Style Transfer</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[Why am I Chucking the Tensorflow Queue based Data Input Pipeline]]></title>
            <link>https://medium.com/data-science/why-am-i-chucking-the-tensorflow-queue-based-data-input-pipeline-5b4427735a0d?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b4427735a0d</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Sat, 02 Sep 2017 19:02:04 GMT</pubDate>
            <atom:updated>2017-09-05T01:49:23.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V2xuraIrNvGDNUkV.gif" /></figure><p>Post assumes some basic familiarity with Tensorflow. It is mostly me whining over the problems with input pipeline 😆</p><p>I recently hit a soft road block on using the <a href="https://www.tensorflow.org/programmers_guide/threading_and_queues"><strong>old </strong></a>Queue based Tensorflow Data Input Pipeline. Nothing very serious but it just does not seem right from a design perspective. Tensorflow team was indeed aware of the problem with its old design and had an issue (<a href="https://github.com/tensorflow/tensorflow/issues/7951">Issue #7951</a>) raised for a complete design change (in fact, “ start from a clean slate” is what it said in the issue description). At the time I started learning/using the input pipeline the new design was not present (although the issue was already raised.). I thought of continuing with the old design given that I had invested some time both in terms of learning and experimenting.</p><p>I decided to use it in my <a href="https://bitbucket.org/hawk23/trafficsignsense/src">TrafficSignSense</a> (well, now scrapped) project. I created an abstraction because in itself the queue based pipeline was quite spread out. I decided to put it in a “create-kickoff-cleanup” abstraction (for reference):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72ef6659f91397438e8d54d3d277dbf7/href">https://medium.com/media/72ef6659f91397438e8d54d3d277dbf7/href</a></iframe><p>Coming back to the issue, train program looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81ed833e9f1fbd598973b330e2f9698c/href">https://medium.com/media/81ed833e9f1fbd598973b330e2f9698c/href</a></iframe><p>The problem arises when I need to periodically validate my model.</p><pre>eval_list = [train_optimizer, merged_summary, model_loss,              train_accuracy, valid_accuracy]        <br>for i in range(NUM_EPOCHS):            <br>    _, summary, loss, accuracy_t, accuracy_v = sess.run(eval_list)                       <br>    train_writer.add_summary(summary)</pre><p>When we try to evaluate valid_accuracy, not so surprisingly what you get is wrong results. It is basically picking random weights. Note that I am re-creating the model ( model_v = model.CTrafficModel(batch_valid_input, NUM_CLASSES ) and this exactly is the main problem. I had to re-create the model for validation data because that is the only way I can feed data using the input pipeline. I could “perhaps” solve this with checkpoints. But, it does not seem right. I think checkpoint as something to be output of a training-validation process and to be used during inference time or in case of training resume. Training and validation are tightly coupled and I don’t like the idea of dumping weights and reloading them every few iteration for the sake of validation. I also don’t like the idea of re-creating the model just because the data changed (given the model has remained the same).</p><p>The above are just a couple of problems with the old design of input pipeline. The filed issue describes a lot of other associated problems . I finally decided to do away with it for good.</p><h4>So, what next?</h4><p>Well, as a replacement Tensorflow has the Datasetand Iterator APIs for creating input pipelines without a lot of struggle (that is what they say). I am yet to go through them. Tensorflow also has these Estimatorand Experimenthigh level abstractions. I plan to use them along with the Dataset-Iterator . Hope they make the task at hand easy!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b4427735a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-am-i-chucking-the-tensorflow-queue-based-data-input-pipeline-5b4427735a0d">Why am I Chucking the Tensorflow Queue based Data Input Pipeline</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[Andrew Ng is back. This time with Deep Learning:)]]></title>
            <link>https://medium.com/@hawking23/andrew-ng-is-back-this-time-with-deep-learning-193ef254eb99?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/193ef254eb99</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mooc]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Fri, 18 Aug 2017 19:59:53 GMT</pubDate>
            <atom:updated>2017-08-27T06:37:58.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>Andrew Ng is back. This time with Deep Learning :)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzvKd_raY6x134pEHMhbFQ.jpeg" /></figure><p>May be I am late to the party. May be the title is not as cheesy as it needs to be. Cut me some slack. It is 1:17 in the night(or morning?)and I am half sleepy.</p><p>So I happened to complete this simple yet very informative course. I have seen people complete all three (at the time of writing this post three out of five courses are open) courses in just a couple of days. So, as I said I might be late to the party. In any case I thought I would present my views. Well, why not, we live in a free world :)</p><p>The course in itself is pretty simple but very well structured. If you are someone who has already taken Ng’s ML course then this one should be possible without much hurdles. If you have high school level knowledge of differential calculus then it would be great although it is not absolutely necessary.</p><h4>A few points that I liked about the course:</h4><p>1) Obviously Andrew’s signature teaching style.<br>2) The stress on Notations. It systematically establishes the notations. It imprints in your brain.<br>3) Assignments are very well structured following a bottom-up approach. Build pieces first and then combine them. This should be helpful for beginners.<br>4) Logistic regression as a computation graph (and as a neural network) was a really good motivation for Neural Networks as a whole.<br>5) Although not a complete insight into back propagation still a major amount is covered without making it look monstrous.</p><h4>One of the things that could have been better:</h4><p>While I liked the structuring of the assignments I felt a lot of it was a fill in the blank type(I have similar complaint with the ML course as well). There is not much scope to make mistakes. Also it does not give a complete feel of writing a piece of software. <br>But, may be that is not the right expectation to have. Many, perhaps would not want to write boilerplate. Also this course is not about Software Engineering. It does a good job in providing the adequate knowledge to motivate you to explore further. It is more about enhancing/building your basics.</p><p>All in all a nice course for beginners. I would say must take for beginners. Even for the experienced it is an opportunity to keep your Tensorflows and Pytorchs aside for some time and experience raw numpy and python.</p><p>Link to Neural Network and Deep Learning: <a href="https://www.coursera.org/learn/neural-networks-deep-learning/home/welcome">here</a></p><p>Link to the whole Specialization: <a href="https://www.coursera.org/specializations/deep-learning">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193ef254eb99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low Precision Inference with TensorRT]]></title>
            <link>https://medium.com/data-science/low-precision-inference-with-tensorrt-6eb3cda0730b?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb3cda0730b</guid>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 17:43:01 GMT</pubDate>
            <atom:updated>2018-11-25T04:56:08.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: This is <strong>not </strong>an official NVIDIA post. Just a summary of whatever I have learnt and gathered from presentations, talks I have listened to and interaction with people. Post assumes some basic familiarity with Deep Learning(DL).</p><p>A Deep Learning program typically has two stages, viz.,</p><ol><li>Training, where with a bunch of data and certain optimization techniques, the machine learns to generalize (well, that is as simple as it can get). Normally done offline.</li><li>Inference, where the machine applies the learned generalization on unseen data. Normally used in a production environment.</li></ol><p>Training is an iterative process on a large set of data. It is quite computationally intensive. Anything from a single GPU to a farm of GPUs is used depending on the problem definition, data etc.</p><p>On the other hand Inference is “<em>relatively</em>” easy on computation(owing to smaller batch sizes and no backward pass) but it is still a difficult problem to achieve real time inference on most of the DNN (Deep Neural Network) applications.</p><p>Note that the training process does not have the constraint of “<em>real time</em>” in general. Practical inference on the other hand is time and power (especially in embedded) bound. TensorRT is Nvidia software solution for generating optimized models for production deployment of Deep Learning Models. This <a href="https://devblogs.nvidia.com/parallelforall/production-deep-learning-nvidia-gpu-inference-engine/">parallel forall</a> blog post has a very good introduction to TensorRT (TRT, formerly was called GPU Inference Engine (GIE) and the blog uses the old lingo).</p><p>This blog would concentrate mainly on one of the important optimization techniques: <strong>Low Precision Inference (LPI)</strong>.</p><p>Before proceeding to understanding LPI, I will quickly summarize the parallel forall blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*7zvHEeYhiHBqjO_pzlWKww.png" /><figcaption>Fig. 1: TensortRT in one picture</figcaption></figure><p>The above picture pretty much summarizes the working of TRT. It is basically exposed as an <a href="https://developer.nvidia.com/tensorrt">SDK</a>. You input your already trained network (this would imply model definition and learned parameters) and other parameters like inference batch size and precision, TRT does optimization and builds an execution plan which can be used as is or serialized and saved to disk and used at a later time. No Deep Learning framework required at Inference time. Just use the execution plan output by TRT and you are good to go. Use it on servers, Desktops or even on Embedded. And moreover, for a given model this a one time thing. No strings attached :)</p><h4>The Optimization Engine</h4><p>This is where the magic happens (well, not really, its just science). TRT does several optimizations.</p><ul><li>Graph optimizations:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*PyNcjHKZ8rQ48QCPsdQ9wA.png" /><figcaption>Fig.2: Vertical Fusion — Input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*bJts223Qo55toZ9AY60Ruw.png" /><figcaption>Fig.3: Vertical Fusion — Optimized graph</figcaption></figure><p>The above figures explain the vertical fusion optimization that TRT does. The Convolution (C), Bias(B) and Activation(R, ReLU in this case) are all collapsed into one single node (implementation wise this would mean a single CUDA kernel launch for C, B and R).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKwCx_lq-oHcLYkI.png" /><figcaption>Fig.4: Horizontal Fusion</figcaption></figure><p>Yes. There is also a horizontal fusion where if multiple nodes with same operation are feeding to multiple nodes then it is converted to one single node feeding multiple nodes. The three 1x1 CBRs are fused to one and their output is directed to appropriate nodes.</p><h4>Other optimizations</h4><p>Apart from the graph optimizations, TRT, through experiments and based on parameters like batch size, convolution kernel(filter) sizes, chooses efficient algorithms and kernels(CUDA kernels) for operations in network.</p><h3>Low Precision Inference</h3><h4>So, why do we really need inference at low precision?</h4><p>Well, as mentioned already execution time and power are not cheap and are critical in real time applications. Given the amount of compute required we would like to optimize our inference in favor of time and power without hurting the accuracy. So, we move to a 8 bit representation of parameters and activation at inference time. 8 bit would need lesser cycle for memory fetch compared to 32 bit. There is also one other advantage in the form of a new hardware instruction (DP4A) which I will address later in this post.</p><h4>Does that work?</h4><p>Yes, of course. This blog would have been a waste of time if not :). During the process of training, parameters and activation are represented in <a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format">FP32</a>. FP32’s high precision fares well for training as every training step corrects the parameters by small amount. DL algorithms are in general resilient to noise. During the course of learning the model, in general, tries to selectively preserve the features necessary for prediction. So, throwing out unnecessary stuff is kind of built into the process. So we hope that the noise introduced by low precision representation is thrown away by the model (again, very layman terms here). As far as I know there is no rigorous mathematical proof which says low precision should work as good as FP32 during inference.</p><h4>Mapping FP32 to 8-bit</h4><p>This is something that TensorRT does for the app/client. The app/client just needs to implement an interface which provides calibration information and some caching related code. More on this soon. Before that lets see the steps TRT follows to do the 32-bit to 8-bit mapping.</p><p>The candidates for mapping are Inputs to each layer (which would be input to first layer and activation for the rest) and learned parameters. The simplest form of mapping/quantization is a linear quantization.</p><p><em>FP32 Tensor (T) = scale_factor(sf) * 8-bit Tensor(t)</em> <em>+ FP32_bias (b)</em></p><p>Simple, isn’t it? Lets make it simpler. Turns out (from experiments) that the bias term does not really add any value. So, get rid of it.</p><p><em>T = sf * t</em></p><p>Note that <em>sf </em>here is the scaling factor for each tensor in each of the layers. Now, the next problem is to find the scaling factor. One simple approach is to do as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*_36xi1OWq9zQ8cydVVWCpA.png" /><figcaption>Fig.5: A simple max-max mapping</figcaption></figure><p>We simply map the -|max| and |max| FP32 value in a tensor to -127 and 127 respectively. The rest of the values are linearly scaled accordingly. But, there is a problem here. Experiments show that this kind of mapping results in significant accuracy loss. So, TRT does the following instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*1tk6ai9FVV9Debbha2lbkQ.png" /><figcaption>Fig.6: Threshold instead of max</figcaption></figure><p>Instead of looking at the |max| values. Fix a threshold (how? we will see that later). and then do the mapping as previous. Any value that lies of the threshold is adjusted to either -127 or 127. For eg., in the above figure the three “red crosses” are mapped to -127.</p><p>So the next question is what is the optimal value of threshold <em>T</em>? We have two distributions here. We have FP32 tensors that are best represented in FP32 distribution. But, we want to represent them in a different distribution(8-bit) which is not the best distribution. We want to see how different these distributions are and want to minimize the difference. TRT, uses Kullback-Leibler divergence (<a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">KL-divergence</a>) to measure the difference and aims to minimize it.</p><p><strong>Optional: What is KL-divergence? Why KL-divergence? Some Intuition: &lt;Optional Begins&gt;</strong>Lets jump into coding theory a bit here. Say I have a series of symbols and I know the probability of their occurrence. If I were to encode the symbols optimally I would use say, ‘<em>T</em>’ bits. Note that <em>T</em> is the optimal number of bits. Lets call this code, Code ‘<em>A</em>’. Now, I have same set of symbols but their probability of occurrence has changed. Now, with symbols having new probability, if I use code ‘<em>A</em>’ to encode the symbols the number of bits for encoding will be sub-optimal and greater than ‘<em>T</em>’. KL-divergence precisely measures this difference, the difference between the optimal and sub-optimal (due to choosing a wrong code). In our case the right code for our tensor values is FP32 but we are choosing to instead represent in 8-bit, wrong code (well, not wrong wrong but you get the point). So there is penalty which is measured by KL-divergence. Our job is to minimize the penalty. If you are someone who has solved some problems using DL you might have used cross-entropy as a cost function. KL-divergence is closely related to cross-entropy. While KL-divergence represents the difference in number of bits (or extra bits needed) due to encoding in wrong code, cross-entropy represents the exact number of bits required to encode symbols in that wrong code. So, <em>KL-divergence = (cross entropy) — (number of bits required in the optimal code)</em>. <strong>&lt;Optional Ends&gt;</strong></p><p>So, we need to minimize the KL-divergence between FP32 values and corresponding 8-bit values. TRT, uses a simple iterative search for minimum divergence rather than say gradient descent based methods . The steps are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*MYjwfp6SxxuJvOlZJnKIlg.png" /><figcaption>Fig.7: Threshold finding process</figcaption></figure><h4>Calibration</h4><p>TRT, employs experiment based iterative search for threshold values. Calibration forms a main part of it. The application/client provides TRT a sample dataset (ideally subset of Validation set) called the “calibration dataset” which it uses to do what is called a Calibration. TRT, runs <strong>FP32</strong> inference on the calibration dataset. Collects histograms of activations and generates a <strong>set</strong> of 8-bit representations with different thresholds and chooses the one which has the least KL-divergence. The KL-divergence is between the reference distribution (which is the FP32 activations) and the quantized distribution(which is the 8-bit quantized activations). TRT 2.1 provides IInt8EntropyCalibrator interface which needs to be implemented by the client to provide calibration dataset and some boilerplate code for caching the calibration results.</p><h4>DP4A</h4><p>So, that was in brief about how TRT goes about doing optimization. There is one more thing which is not exactly related but TRT relies on for fast inference with 8-bit. Starting from Pascal generation GPUs (selected SKUs) there is a new Hardware instruction called DP4A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*fgyi_gAhpTjPOs8Igutucg.png" /><figcaption>Fig.8: DP4A (<strong>D</strong>ot <strong>P</strong>roduct of <strong>4</strong> 8-bits <strong>A</strong>ccumulated to a 32-bit)</figcaption></figure><p>It is basically one instruction which does 4 8-bit multiplications and accumulates into a 32-bit int. Dot product forms the basis of math in Convolution operation and this instruction gives a very good boost by minimizing execution time and power consumption. <a href="https://devblogs.nvidia.com/parallelforall/mixed-precision-programming-cuda-8/">This</a> blog on CUDA 8 discusses DP4A in more detail. Do check it out if interested.</p><p>So, all in all there is plenty of scope for optimization. Given TRT’s optimization and the right HW (GPU which supports DP4A) you can not only push the GPU to its limits but at the same time keep it efficient. So go do some efficient inference until you infer the meaning of life :D</p><p><strong>Some references: </strong>I have shamelessly copied the figures from blogs and presentations :)</p><p>Fig.1 through 4 : <a href="https://devblogs.nvidia.com/parallelforall/deploying-deep-learning-nvidia-tensorrt/">TensorRT</a></p><p>Fig.5 through 8 : <a href="http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf">GTC PPT</a></p><p>Most of this is based on this excellent <a href="http://on-demand.gputechconf.com/gtc/2017/video/s7310-szymon-migacz-8-bit-inference-with-tensorrt.mp4">presentation</a> at GTC-2017.</p><p>PS: Feel free to comment/criticize/ ♥ the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb3cda0730b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/low-precision-inference-with-tensorrt-6eb3cda0730b">Low Precision Inference with TensorRT</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[Thinking in the Hough Space: The Doing]]></title>
            <link>https://medium.com/buzzrobot/thinking-in-the-hough-space-the-doing-d17a13e068fe?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d17a13e068fe</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[self-driving-cars]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Sat, 08 Jul 2017 16:05:54 GMT</pubDate>
            <atom:updated>2018-11-25T04:59:15.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*s6o9YpiHoub43GGlek75mw.jpeg" /></figure><p>My previous post <a href="https://medium.com/@hawking23/thinking-in-the-hough-space-the-thinking-ea56bd2a8014">Thinking in the Hough space: The Thinking</a> was a brief explanation of Hough transform for line detection. I wanted to do a small project with line detection. What better than Lane Detection (autonomous cars are a hot topic you see)? I made a simple program for basic lane detection.</p><p>The relevant code can be found here: <a href="https://bitbucket.org/hawk23/lane_detection">Lane Detection</a></p><p>Before starting, I just need to add here that one other reason for doing this project is Udacity Course on Self-Driving Cars(<a href="https://in.udacity.com/course/self-driving-car-engineer-nanodegree--nd013/">SDCND</a>). In fact, this is one of the projects in term 1 of the course. I have read several awesome blog posts by SDCND students and it inspired me to do this project. I have borrowed the demo videos from the course github repository over <a href="https://github.com/udacity/CarND-LaneLines-P1">here</a>. For the sake of record, I am not a SDCND student… yet ;)</p><h4>Lets define the problem…</h4><p>We have a camera fitted to a car which captures the road ahead. The goal is to analyze the video feed and draw lane demarcations to denote the right and left ends of the lane in which the car is currently moving. For practical purposes (FWIW, I don’t own a car :)) we do analysis on prerecorded videos(remember? I said I will use videos from Udacity course).</p><h4>OK. So what tools do I need?</h4><p>Very minimalist:</p><ol><li>python</li><li>numpy</li><li>OpenCV</li></ol><h4>Great! Lets get started…</h4><p>So, we are given this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX51L3enepCw&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX51L3enepCw&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f45eb9b8622991da8314ab4b0a0112c9/href">https://medium.com/media/f45eb9b8622991da8314ab4b0a0112c9/href</a></iframe><p>and the target is this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS_GOZO7hYUY&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS_GOZO7hYUY&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/480c091ee170c14b261aa330c20f1a82/href">https://medium.com/media/480c091ee170c14b261aa330c20f1a82/href</a></iframe><p>From the title it is apparent that Hough transform is at the core of the solution. But, we need to do a bunch of pre and post processing to get an effective result.</p><p>Lets start from the first step, that is reading the video:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f2fcbaeb9c479fef7ffe2f4d0cc8c1/href">https://medium.com/media/88f2fcbaeb9c479fef7ffe2f4d0cc8c1/href</a></iframe><p>This piece of code above basically checks if there is a console video input file and if not then it takes the video file which is part of the repository. cv2.VideoCapture() basically helps you to open a video (file, feed from camera etc.). In our case it reads a video file. There is code to dump the final output. This is guarded by DUMP variable. If our CVideoCapture was successful then it implies the video has been successfully opened. We read video frame-by-frame in a loop until there is nothing to read. video_in.read() gives us the current frame.</p><p>Next, we do some pre processing on our input frame (this is as good as an image for the purpose of this problem). In majority of the cases lane lines are either white or yellow in color. We would not want to waste our processing power and time on unnecessary pixels. Also the unnecessary pixels have an impact on the outcome of the hough transform. So, we zero out them(blackened).</p><pre>YELLOW_LOW  <strong>=</strong> np<strong>.</strong>asarray([20, 100, 100]) <br>YELLOW_HIGH <strong>=</strong> np<strong>.</strong>asarray([30, 255, 255])<br>WHITE_LOW   <strong>=</strong> np<strong>.</strong>asarray([0, 0, 230])<br>WHITE_HIGH  <strong>=</strong> np<strong>.</strong>asarray([255, 80, 255])</pre><p>We use a low and high threshold for both white and yellow. Note that currently we are operating in the <a href="https://en.wikipedia.org/wiki/HSL_and_HSV">HSV </a>domain. With low and high we have got an acceptable range for <em>H, S </em>and<em> V </em>values. Any pixel whose <em>H, S, V </em>components do not fall into this range are zeroed out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6IAX6NSh0_Yj6X16fk0iiw.jpeg" /><figcaption>Input image processed with color threshold. Threshold for Yellow and White</figcaption></figure><p>More information on HSV space can be found here: <a href="https://en.wikipedia.org/wiki/HSL_and_HSV">HSV</a>. You can play around with threshold for a better color threshold if needed. Beware that HSV is described in a cylindrical geometry. From here on we operate on the grey scale. The ‘V’ channel, frame_hsv[2]is a close approximation to grey scale and that is being used here.</p><p>If the camera position is “fixed and known” beforehand then we can do some more optimization to improve the speed and accuracy of the detection.</p><pre># Carve out unnecessary region in the frame<br>pts = np.array([[(0,0), (0, frame_h), (frame_w/2 - 25, frame_h/2 +               25), (frame_w/2 + 25, frame_h/2 + 25), (frame_w, frame_h), (frame_w, 0)]])<br>cv2.fillPoly(frame_grey, pts, 0)</pre><p>Parts of the image like, the sky or extreme left and right portions are not useful in determining the lanes. In fact, we can carve out a very specific area where there is an almost 100% chance that both the lanes will lie. We define a polygon represented by its points pts. We zero out this entire polygon as it is <strong>not</strong> the region where the lanes that we are interested could possibly lie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FqP6LermdAf9JG5ZMR5VXQ.jpeg" /><figcaption>Leftover frame after carving out unnecessary region</figcaption></figure><p>You can compare this image with the previous and see that a lot of components like sky, some obscured cars in the left are no longer present and we have a cleaner image.</p><p>You must remember from the previous post that Hough transform would need Edge points as inputs (remember, edge points in Image space are lines in Hough space stuff?). So we will go ahead and do some more processing on the above image before applying the hough transform.</p><p>We will use Canny edge detector to determine the edge points. Canny edge detector is an intelligent edge detector built on top of detectors like sobel operator. If you are interested you should really check out the Edge Detection lesson in <a href="https://classroom.udacity.com/courses/ud810">Intro to Computer Vision</a>. So our image looks as such after applying Canny:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*44AU0xDrTf3FtnAgH1l9TQ.jpeg" /><figcaption>Edge Image using Canny Edge Detector</figcaption></figure><p>You can see that the edges are distinctly marked with just almost one pixel wide lines. That is the beauty of Canny Edge detector.</p><p>Well, that is it for pre-processing. We will use the Canny output as input to Hough transform.</p><pre>lines_list = cv2.HoughLinesP(frame_in, RHO_ACCURACY, THETA_ACCURACY,                  MIN_VOTES, MIN_LINE_LENGTH, MAX_LINE_GAP)</pre><p>We will use the OpenCV HoughLinesP function. You can get a detailed documentation <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html">here</a>. Note that this function slightly differs from the actual Hough implementation (which, by the way, in OpenCV is HoughLines). This is probabilistic Hough, wherein, not all edge points are considered for line determination rather a random subset of points are considered.</p><ul><li>frame_in: Input frame. In this case, the output from Canny.</li><li>RHO_ACCURACY: The granularity of the distance parameter(d).</li><li>THETA_ACCURACY: The granularity of the angle parameter(t).</li><li>MIN_VOTES: Minimum votes that a (d, t) pair should get to be considered for line.</li><li>MIN_LINE_LENGTH: Minimum length of line.</li><li>MAX_LINE_GAP: Maximum allowed gap between line segments to treat them as single line.</li></ul><p>The function returns a numpy array containing <em>n</em> numpy arrays each of which have 4 values [<em>x1, y1, x2, y2</em>]. (<em>x1, y1</em>) and (<em>x2, y2</em>) represent the line. Now we have many such lines. But we are interested in just the left and right lanes. So a max of two lines representing our left and right lanes. To do this we do some post-processing on our Hough result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e77916054ad9107d63ea498ab1657f/href">https://medium.com/media/54e77916054ad9107d63ea498ab1657f/href</a></iframe><p>We do not know the exact slope values of the lines representing the lanes. But, what we know for sure is that the lanes would not have certain slopes. We will use a threshold of 0.2 to -0.2 for this. So all lines with slopes in between these are simply ignored. Next we group the points belonging to right and left lanes based on the sign of the slope. A positive slope indicates right lane and negative slope indicates left. Note that we are appending each point individually into right and left list(remember that a line contains two points which are kind of unpacked in this step).</p><p>Technically we are done as we have our right and left lanes . But, there is this representation part where we try to overlay lines on the original video (as seen in the first picture).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4005d3c6bd352df91df2ae2b285f2c/href">https://medium.com/media/af4005d3c6bd352df91df2ae2b285f2c/href</a></iframe><p>We first overlay the right line followed by left. From the previous step we have two lists, viz., right_lane and left_lane. Each of these contain a set of points representing the right and left lanes respectively. We fit a straight line for these points. For this purpose we use OpenCV function fitLine function (documentation <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html">here</a>). In our case this function returns a numpy array with four floats (<em>vx</em>, <em>vy</em>, <em>x0</em>, <em>y0</em>), where (<em>vx</em>, <em>vy</em>) is a vector collinear to the line and (<em>x0</em>, <em>y0</em>) is a point on the line.</p><p>We need two points on the image to <strong>draw</strong> line. We have one point and a vector collinear to our line. The slope of our line is same as the vector (<em>vx</em>, <em>vy</em>) as the vector is collinear to the line. In the line equation <em>y = mx + c</em>, we solve for <em>c</em> with <em>m</em> (slope), <em>y = y0</em> and <em>x = x0</em>. This is encapsulated in get_line_props function. So, finally we have equation of the line.</p><p>There is one last thing. For a better presentation the overlayed lines should start from the bottom and go up to some point in length (refer first picture). In this, I decided to use (<em>x</em>, FRAME_HEIGHT) and (<em>x</em>, FRAME_HEIGHT * 0.65) as the coordinates for the bottom and top respectively. Note that only y-coordinates are fixed. The x-coordinates are calculated using the line equation (look at get_x() function for reference). Also note that the coordinate system is on the top left of the image/frame.</p><h4>Some more results… (Who does not want more!!?)</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F74qj7hmlfaM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D74qj7hmlfaM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F74qj7hmlfaM%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/7bd4f54f24c067808427985961f6acba/href">https://medium.com/media/7bd4f54f24c067808427985961f6acba/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTGP6ZGX8GII%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTGP6ZGX8GII&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTGP6ZGX8GII%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/459529ed37b6f561abaca111af7c6059/href">https://medium.com/media/459529ed37b6f561abaca111af7c6059/href</a></iframe><h4>OK. That was a bit long. Lets wrap up, shall we?</h4><p>Yup, time to wrap up. It was a nice experience doing this project. I must add here that this is no SOTA implementation. In fact, I would treat this as an hello world for Lane Detection. This was one of the reasons I guess I did not have major hiccups doing this. OpenCV and numpy really do a lot of heavy lifting.</p><p>There are plethora of improvements that can be done. If you see the videos you realize that in cases like broken lanes or curved lanes the accuracy is not so good. We could try fitting a polynomial in place of a straight line (I hope this would solve curve lanes to some extent). I did a little bit of literature survey before hopping on to program it. The <a href="http://www.vision.caltech.edu/malaa/publications/aly08realtime.pdf">paper</a> based on Inverse Perspective mapping and B-spline fitting stood out and I would love to learn and implement it some time. For now, I guess I am good with this hello world.</p><p>Feel free to comment/criticize/ ♥ the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d17a13e068fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/buzzrobot/thinking-in-the-hough-space-the-doing-d17a13e068fe">Thinking in the Hough Space: The Doing</a> was originally published in <a href="https://medium.com/buzzrobot">BuzzRobot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking in the Hough Space: The Thinking]]></title>
            <link>https://medium.com/buzzrobot/thinking-in-the-hough-space-the-thinking-ea56bd2a8014?source=rss-a83b80da731f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea56bd2a8014</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-vision]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Vignesh Ungrapalli]]></dc:creator>
            <pubDate>Tue, 13 Jun 2017 18:10:23 GMT</pubDate>
            <atom:updated>2017-12-21T04:29:37.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Kazm9CpLM4bhFjIuH7fxQw.png" /><figcaption>An example outcome of applying Hough Transform to detect Lines.</figcaption></figure><p>It is amazing how changing our perspective can lead to making a difficult problem strikingly simple. This is not only applicable to life but also applicable in Computer Science (that wasn’t surprising, was it?). As I am no philosopher (although I would definitely like to study philosophy), I will stick to Computer Science and this blog is on one such problem where a perspective change gives a simple solution for a seemingly difficult problem.</p><h4>Lets define the problem…</h4><p>The objective is, given an Image (or a Video for that matter), find, in the Image a particular predefined shape. Now that is something very generic. A special case is given an Image, find lines or circles (analytically definable shapes). This is where the Hough transform comes in.Lets look at how Hough transform can be used to detect lines. Circle detection follows similar logic.</p><h4>Some background</h4><p>We know that a line can be described in an <em>x</em>-<em>y </em>space based on the two parameters, viz., intercept(<em>c</em>) and slope (<em>m)</em>. In the context of Image lets calls this the ‘Image Space’ (think something like laying out our image on this plane). Now lets look at a different manifestation of the above space. What if we create an <em>m</em>-<em>c </em>space instead of an <em>x</em>-<em>y </em>space? You can see that the lines in <em>x-y</em> space are represented as points in <em>m-c</em> space. Lets call this <em>m-c</em> space, the Hough space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV30YY-wPKzxv-4TM-jm2Q.jpeg" /><figcaption>Line in Image space is a point in Hough space.</figcaption></figure><p>Great! So you might have guessed where we are heading up to. Yup, the duality holds. A point in the Image space is a line in the Hough space. A point in the Image space can take infinitely different values of <em>m</em> and <em>c</em>. Hence, the point representation is a line in the Hough space. The below figure shows something interesting which will help us find the lines in our image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AY0h2qnOQQLZYgI4r_0EnA.jpeg" /><figcaption>Points on same line in <em>Image</em> space pass through same point in Hough space</figcaption></figure><p>All the points on a particular line in Image space pass through a single common point in the Hough space and this is how we will find our lines in the image. A minor modification before we proceed ahead. Instead of using the slope-intercept (<em>y = mx + c</em>) representation of line we will use the polar representation (<em>d = xcos(t) + ysin(t)), t </em>is the angle between the positive <em>x</em>-axis and the normal to the line. <em>d</em> being the distance of the line from origin.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-841S-rYyFwSl0Bq2DNDew.jpeg" /><figcaption>Polar representation of line</figcaption></figure><h4>But, how exactly?</h4><ol><li>We will initialize a 2-D array of size <em>|d|</em>(the range of <em>d</em> values)<em> </em>and <em>|t|</em>(the range of <em>t</em> values)<em>. </em>This is called the Hough accumulator array (<em>H</em>). This array basically maintains the number of votes each d,t pair scores.</li><li>We need a Edge image as we would like to not have points which are unnecessary. An edge image gets rid of all unnecessary/redundant points. Normally a Canny edge operation is done on the original image.</li><li>Now we run through each of our edge points and for each edge point we solve for <em>d</em> in the range of <em>t</em>. That is run through all the values in <em>|t|</em> range and solve for <em>d </em>in the polar line equation. Increment the counter in the position <em>H[d, t].</em></li><li>After all the edge points are done, look for the maximum in the Hough accumulator array(<em>H</em>). The corresponding <em>d </em>and <em>t </em>values are the values that we struggled for :)</li></ol><p>Isn’t it cool?! It is great if you can implement Hough transform from scratch. But, if you are not one of them and would want to use it as a tool then OpenCV provides utilities for this. In the next part (<a href="https://medium.com/@hawking23/thinking-in-the-hough-space-the-doing-d17a13e068fe">Thinking in the Hough Space: The Doing</a>) I will write about “Lane Detection” using Hough transform. We will also see some code for the same in OpenCV with python.</p><p>For a still better understanding of Hough transform you can go through this lesson from CV course at Udacity: <a href="https://classroom.udacity.com/courses/ud810/lessons/2870588566/concepts/34824487880923">Udacity CV</a> . The course is awesome and the professor has a great sense of humor :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea56bd2a8014" width="1" height="1" alt=""><hr><p><a href="https://medium.com/buzzrobot/thinking-in-the-hough-space-the-thinking-ea56bd2a8014">Thinking in the Hough Space: The Thinking</a> was originally published in <a href="https://medium.com/buzzrobot">BuzzRobot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>