<?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 Elvis Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Elvis Ferreira on Medium]]></description>
        <link>https://medium.com/@elvisdias?source=rss-1c41739d572f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*T5I6C5kLYaLrNHTs.</url>
            <title>Stories by Elvis Ferreira on Medium</title>
            <link>https://medium.com/@elvisdias?source=rss-1c41739d572f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:14:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elvisdias/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[Color quantization with Kmeans in OpenCV]]></title>
            <link>https://medium.com/@elvisdias/color-quantization-with-kmeans-in-opencv-99dbd0bde91b?source=rss-1c41739d572f------2</link>
            <guid isPermaLink="false">https://medium.com/p/99dbd0bde91b</guid>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Elvis Ferreira]]></dc:creator>
            <pubDate>Sun, 12 May 2019 21:20:16 GMT</pubDate>
            <atom:updated>2019-05-15T17:26:26.276Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the last part of this series sharing some homework results proposed by a graduation computer vision class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*du_JjNC1rjvF5Wgn3W4NZg.jpeg" /><figcaption>Illustration of matter organized in groups, also called clusters. (<a href="https://www.analyticsindiamag.com/is-k-means-clustering-really-the-best-unsupervised-learning-algorithm/">source</a>)</figcaption></figure><h4>Theory</h4><p>For this last implementation we are going to be using a technique for data clusterization and with that generate new images with a reduced number of colors comparing to the original image.</p><p>Ok, first things first, quantization: is a way to represent data from a large set in a smaller set. This goal is usually useful for data compression, however can be used in digital images too; As stated on <a href="https://en.wikipedia.org/wiki/Quantization_(image_processing)">wikipedia</a>, “Color quantization reduces the number of colors used in an image; this is important for displaying images on devices that support a limited number of colors and for efficiently compressing certain kinds of images.”</p><p>The quantization basically works by grouping color that look similar together. If we specify that we only want to show the picture in 4 colors, the quantization will try to see where each pixel color should fit in those four colors and then rearrange the image.</p><p>From the many quantization algorithms that there are, we will be working with one of the most used and famous one: Kmeans. The simple algorithm partitions the n-dimension space (of data) in Voronoi’s cells, each cell having an specific center. So, for example, if we have a many labels for a given data, but we want to represent them only by three unique groups, this algorithm finds how to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*KV7q9k9Kf44djmU-0svQqQ.jpeg" /><figcaption>Kmeans example (<a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwithqLgyZPiAhUdF7kGHVfoDQ8Qjxx6BAgBEAI&amp;url=https%3A%2F%2Fwww.mathworks.com%2Fmatlabcentral%2Ffileexchange%2F24616-kmeans-clustering&amp;psig=AOvVaw1im-3GXsBewTdRkzCQpWY-&amp;ust=1557667487142328">source</a>)</figcaption></figure><p>The groups, called clusters in data analysis, are formed based on the distance in space from the sample to the cluster’s center (determined either by the user or randomly), the smallest distance tell the samples’ cluster.</p><p>The algorithm can be easily summarized by a few steps:</p><ol><li>Pick a <strong>k</strong> as the number of clusters desired for the array x[i] of N samples i=1,2,⋯,N.</li><li>Choose c1, c2, ⋯, ck as the initial centers for each cluster.</li><li>Classify each sample x[i] calculating the minimum distance (i.g. euclidean distance) in space to each center.</li><li>Re-define each cluster center based on the step 3: for each cluster now full of samples, should there be another center points, the mean of all samples in space.</li><li>If the new means (centers) are consistent, didn’t change much, end of the algorithm. Otherwise, after redefining the new centers, reclassify the samples (back to step 3).</li></ol><p>Another approach to this algorithm is to initialize the centers randomly. This way, the clusters will eventually converge to the clusters we expect by specifying the centers ourselves, however given after the algorithm runs for some rounds. This is a particularity of this algorithm, depending on the parameters it can present different result and may be unsatisfying.</p><p>First we will implement the algorithm with a few rounds and 8 clusters, so that our resulting image is represented only in 8 colors. The base image is from a plate of sushi made of many different colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RmuQ6AUs5We77V09gE5XPA.jpeg" /></figure><p>The Kmeans is not implemented by hand, once again there is a buit-in function in openCV that does it for us. The <a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html">documentation</a> itself already has an example of image quantization through kmeans, however we are doing our implementation here to analyse results.</p><p>The function <em>cv2.kmeans(float samples, k clusters, </em><strong><em>None</em></strong><em>, criteria, n rounds, way to initialize centers) </em>is pretty straight forward explained in the documentation, but oddly for openCV 3+ the documentation does not specify a necessary argument, used in their examples, required in our implementation: the None argument is assumed None everywhere in the documentation and no mentioned anywhere what it should mean.</p><p>Even so, let’s get it working.</p><h4>Implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4becafaf69c078b83d4192e4c6186be/href">https://medium.com/media/d4becafaf69c078b83d4192e4c6186be/href</a></iframe><p>First off we define two variables to determine the number of clusters and rounds. The n rounds it’s good to vary to see how quickly the algorithm converge, and not waste computation.</p><p>After reading the sushi image, in color, we generate a matrix of height*width (sushi size) lines by three columns so we can store every color from each color channel in a way that every line has a [B G R] value. <em>note: need to be type float, int values will round the colors and affect the kmeans calc.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4becafaf69c078b83d4192e4c6186be/href">https://medium.com/media/d4becafaf69c078b83d4192e4c6186be/href</a></iframe><p>The kmeans function returns 3 results, which of we are going to use only labels e centers: labels is how every sample from “samples” is labeled, from 0 to NCLUSTERS, and centers where each label is centered in space. The criteria we pass is the criteria to stop the algorithm: <em>(type of termination, n iterations, accuracy).</em></p><p>For the type of termination we chose to use <em>cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, </em>meaning that we want the algorithm to stop either if the accuracy is reached or the number of iterations has passed. For the flags argument was first implemented passing KMEANS_PP_CENTERS, calculating then the centers based on an algorithm proposed by <a href="http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf">Arthur2007</a>. The rest of the parameters should be self explanatory.</p><p>The three lines of code following kmeans’ call are for creating a new image based on the clusters created for the colors (code took from the openCV documentation), and now we can see the results for the quantization with only NCLUSTERS colors possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*i_MI1HxGrguLWAUIPSdJxg.jpeg" /><figcaption>Quantization with nclusters = 8</figcaption></figure><p>The result is a very interesting image, almost like a painting. To add more details to it (more colors) or not we only need to change a single parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XfOG6sHzHhYuChBbrV1Zuw.jpeg" /><figcaption>Quantization with nclusters = 4</figcaption></figure><p>Ok, now let’s analyse a little deeper. When the code shown above is executed it returns always the same image as result, great right? But as we discussed above this is a not a rule for the kmeans algorithm, this is assured by a set of parameters found for an specific problem. For this problem we first determined nrounds = 5, so the algorithm runs more than one time over the same data and that already assures most of the accuracy, but also the stopping criteria is responsible for this; it’s important to know when the algorithm is ready to stop.</p><p>For a last statement here, we ran the same algorithm but now with NROUNDS = 1 and the center initialization random (cv2.KMEANS_RANDOM_CENTERS), expecting the results to change from result to result.</p><p>The reason for this should be trivial, centers initialized randomly will attract different samples in space for every run and create different clusters data. By that meaning, on the image quantization perceptive, colorize the result image differently every time.</p><p><strong>BUT</strong>, huge but needed, this was not the case. The algorithm didn’t show any randomness in results when applied to the new parameters and this is probably due to the library&#39;s implementation.</p><h4><strong>Discussion</strong></h4><p>First of all, the problem is big enough to be exposed to the randomness. There are many colors in the original image, and they should be grouped differently for different runs (I ran a lot of times).</p><p>Second of all, for testing sake, it was increased the number of clusters, so that maybe the with more frontiers the algorithm would get confused more often; and was reduced the accuracy on the stopping criteria, but nothing showed randomness in the results.</p><p>In conclusion, it was assumed after searching a lot for documentations and examples pointing out this randomness and never finding one, and also by existing a parameter which no one knows what it is in the function call, that the function has flaws in implementation OR in explanation by its official documentation online.</p><blockquote>This should be my last post for this class as professor oriented kinda problems. However, I should be posting more about personal projects or other random studies/hobbies. Thank you so much for reading, leave a comment if you may! :)</blockquote><p>All the codes can be found at my public repository at <a href="https://github.com/elvisdias/Digital-Image-Processing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99dbd0bde91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s work with borders — OpenCV implementation in python]]></title>
            <link>https://medium.com/@elvisdias/lets-work-with-borders-opencv-implementation-in-python-b37c3d87c73a?source=rss-1c41739d572f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b37c3d87c73a</guid>
            <category><![CDATA[georges-seurat]]></category>
            <category><![CDATA[pointillism]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[borders]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Elvis Ferreira]]></dc:creator>
            <pubDate>Wed, 08 May 2019 14:59:35 GMT</pubDate>
            <atom:updated>2019-05-23T19:44:00.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s play with image borders on OpenCV</h3><p>This is a part four series that I’ve been doing for my graduation computer vision class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mlMY0naTG6Is3pojOoodQ.jpeg" /><figcaption>Geroges Seurat “The Seine at La Grande Jatte” (<a href="https://commons.wikimedia.org/wiki/File:Georges_Seurat_026.jpg">source</a>)</figcaption></figure><h4>Canny’s Algorithm</h4><p>For this particular one, we are going to be working with the most used algorithm for border detection and also create pointillism based paintings. Canny’s algorithm for border detection is known as one of the most efficient and fast methods to find discontinuity in digital images, producing as the processing result a binary image, which pixels are white for borders and black for everything else.</p><p>Just as a brief introduction to the algorithm, it searches for gradient’s local maximums for the image. As my professor pointed out <a href="https://agostinhobritojr.github.io/tutorial/pdi/#_descri%C3%A7%C3%A3o_do_programa_pontilhismo_cpp">here</a>, or OpenCV’s <a href="https://docs.opencv.org/3.1.0/da/d22/tutorial_py_canny.html">documentation</a>, Canny’s can be summarized in a few steps:</p><ol><li>Convolution with the Gaussian filter (<a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-ii-6c5a12292587">part 2</a>), calculate the magnitude and gradient’s angle.</li><li>Sharpening gradient’s large crests</li></ol><ul><li>Points classification as the orientations horizontal/vertical as+45°/-45° (±22.5° intervals).</li><li>Check neighbors gradients for the determined orientation.</li><li>Suppression of non maximums: If the gradient’s magnitude M(x,y) is less than any of your neighbors, do g(x,y)=0; otherwise, do g(x,y)=M(x,y) (g(x,y) is the image with suppression).</li></ul><p>3. Hysteresis thresholding usage for breaking contour.</p><ul><li>Used T1 e T2 as variables. T1&gt;T2 (small for threshold 1 and 2).</li><li>If the pixel value has g(x,y)≥T1, this can be seen as a strong border point.</li><li>For the other pixels, g(x,y)≥T2, are weak border points.</li></ul><p>4. All the weak border points’ neighbors search in its 8-neighbors if there is any strong border point. If so, it is treated like part of the frontier.</p><p>5. Canny’s parameters suggestions: H/TL=3/1TH/TL=3/1, ou TH/TL=2/1</p><p>Ok ok, since this summary won’t be implemented, openCV gives it all ready, it serves as an orientation or an idea of how things happen. If you get interested in going deeper, I suggest you to go for a book reading or a better source; now we are starting to program!!!</p><p>An example of the Canny’s detection can be seen on the documentation I linked above, however it’s a fixed border detection. For our implementation, we will have a trackbar to change the parameter T1 and see how it affects the detection.</p><p>The openCV function that does the Canny’s detection can be simply called by <a href="https://docs.opencv.org/3.1.0/dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de"><em>cv2.canny(</em></a><em>src, output image, T1, T2, apertureSize, L2gradient)</em>. For the implementation here we will only be using the mandatory parameters, and changing only T1 (T2 assumed as 3xT1).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a642fc204f143d31a69b0eb708190a9c/href">https://medium.com/media/a642fc204f143d31a69b0eb708190a9c/href</a></iframe><p>We want the bar to change from 0–200 and we initialize the T1 variable as 10. So, after reading Lenna’s picture in b&amp;w we can already call the Canny’s and apply the trackbar to the result. The function setT1 is responsible to keep T1 from going lower than 10 (you will understand in the results), and applying the canny’s to the new values read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*tsyD2U2egSSTECW6u2hQ3Q.png" /><figcaption>T1= 10 (min chosen)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*WkmetIw2eDIW4juQo4Lx3A.png" /><figcaption>T1 = 70</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*q7NEkPdOzwsmXJtHHaOYaw.png" /><figcaption>T1 = 130</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*ouaMXqxpNFSOYjHYXB0yqg.png" /><figcaption>T1 = 200 (max chosen)</figcaption></figure><p>Visualizing we can better understand better how the parameters work on the function and can generate a customized border detection, going from many borders to almost none (weakest to strongest on the picture).</p><h4>Pointilism Art Application</h4><p>Ok great, now for a minute we will introduce another implementation that, for this part’s general purpose, will be merged with the canny’s on the last one. The idea for this one is to paint an image the same color as the one we load in, but with dots. A reference to this idea is the work from the known artist Georges Seurat, reference in this technique.</p><p>Although the art came from creating new images with the dots, we are going to represent a known image in this effect. The solution proposed by my <a href="https://agostinhobritojr.github.io/tutorial/pdi/#_descri%C3%A7%C3%A3o_do_programa_pontilhismo_cpp">professor</a> isn’t to just make a dot on every pixel position, but to have a certain randomness to where it should be placed and also skip some pixels so the frame background color can be perceived and help the illusion.</p><p>For that, first let’s create arrays representing dimensions that will help us skip some pixels, not use the original height and width of the image. The arrays for this are set with dimensions divided by 5. So we are only painting one fifth of the dimension (1 pixel for 5X5 = 25 pixels).</p><p>These arrays are then filled with increment values before having a STEP gain and a tilt to STEP/2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab39c4af2fc0e3fddc3bda7f34c449c/href">https://medium.com/media/7ab39c4af2fc0e3fddc3bda7f34c449c/href</a></iframe><p>Xrange and Yrange have then its sequences randomized, so when we start to paint it doesn’t follow any logical sequence. Before drawing the circle yet we apply some more randomness to the values in the arrays and with that generate the coordinate values for x and y.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54143e8aac80d2413d62690edcc3e8fb/href">https://medium.com/media/54143e8aac80d2413d62690edcc3e8fb/href</a></iframe><p>The built-in function <em>cv2.circle(output, where, radius, color, padding, type of line)</em> is used then to create circle at the x and y that we have in the color of the image we loaded in on that specific spot. The result is printed on a same size image created previously with all white pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*mZyxeJqMB0MOKJem-BvDFA.png" /><figcaption>Pointillism for Lenna’s original picture</figcaption></figure><p>The pointillism effect get’s really interesting because the randomness of the circle drawings together with the quantity of circles allow the background to be perceived and make allusion to hand painted on a real frame. However, the resolution isn’t the better.</p><p>Now, around that, we are going to merge both implementations and try to improve the pointillism resolution. One of the ideas purposed was to apply Canny’s border detection to the pointillism created and for each point of border create new circles; more circles leading to more resolution.</p><p>To start off, we get the same pointillism code, and apply and just call the Canny’s for the result right before applying the pointillism again in the same result but now only on the borders detected.</p><p>Since the Canny’s generates a binary result, we just need to get the pixels that are white and get the gray corresponding to that location in Lenna’s original image to then create new circles upon those pixels in the pointillism image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51ab0f18321fe9c6f4a0a7de8bae5e7b/href">https://medium.com/media/51ab0f18321fe9c6f4a0a7de8bae5e7b/href</a></iframe><p>The code to do that shown above should not be a challenge to be understood if it was clear to you both codes separated. The trackbar was not used here since we would only apply more and more circles to the same image and get a disrupted result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*Pb_FB-U_8rxCBjtG29vcMQ.png" /><figcaption>T1 = 10</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*yhUe8bikSDA4GTkeBCBkQA.png" /><figcaption>T1 = 70</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*ZjxPFqGuNW3sbNo3FVlZhw.png" /><figcaption>T1 = 130</figcaption></figure><p>The result then is as expected better for when we apply Canny’s with a lower value of T1, detecting more borders, so more circles are drawn; The white background gets almost eradicate. The radius was changed to 2 just to get cleaner result.</p><p>That’s it!! On this part we worked with border detection and had a little fun creating art. A cool challenge would be to adapt this code for doing the same for colorful pictures and maybe print it out and expose in a living room as a cool concept. :)</p><blockquote>Thank you for reading, to read more go:</blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-i-9fc72082f230?source=your_stories_page---------------------------">1. Introduction to OpenCV with Python</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-ii-6c5a12292587?source=your_stories_page---------------------------">2. Introduction to OpenCV with Python part II</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-fourier-transform-with-opencv-922a79cddf36">3. Lighting exposure improvement using Fourier Transform with OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/color-quantization-with-kmeans-in-opencv-99dbd0bde91b?source=your_stories_page---------------------------">5. Color quantization with Kmeans in OpenCV</a></blockquote><p>All the codes can be found at my public repository at <a href="https://github.com/elvisdias/Digital-Image-Processing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b37c3d87c73a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Fourier Transform with openCV]]></title>
            <link>https://medium.com/@elvisdias/introduction-to-fourier-transform-with-opencv-922a79cddf36?source=rss-1c41739d572f------2</link>
            <guid isPermaLink="false">https://medium.com/p/922a79cddf36</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[homomorphic-filter]]></category>
            <dc:creator><![CDATA[Elvis Ferreira]]></dc:creator>
            <pubDate>Sat, 04 May 2019 20:22:46 GMT</pubDate>
            <atom:updated>2019-05-23T19:42:46.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lighting exposure improvement using Fourier Transform with OpenCV</h3><p>This is the third part tutorial on a series that I’ve been doing on some computer vision fundamentals using the library OpenCV. All the tutorials presented in the series were proposed by an undergrad computer vision class and implemented in python by choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*LaxggHsWHEsXXabenFABHA.jpeg" /><figcaption><a href="http://photoandtravels.blogspot.com/2011/04/against-light-photography.html">source</a></figcaption></figure><p>This part of the series focus on introducing the usage of the Fourier transform for images with an application for filtering. To this time I haven’t mentioned anything else but spatial image manipulation, however it’s also possible to manipulate images on the frequency domain through the transformation.</p><h4>Fourier Transform</h4><p>The Fourier Transform decomposes a waveform, basically any real world waveform, into sinusoids. That is, the Fourier Transform gives us another way to represent a waveform. For digital images the frequency idea is related to image details, that is, low frequency represents the shapes in general and high frequency more precise details.</p><p>Futhermore, the Discrete Fourier Transform (DFT), used for digital data, presents a new image with noise or imperfections that aren’t easily handle or see on the spatial domain. To exemplify, let’s see how the DFT represents the Moiré pattern, a periodic noise on an image. This pattern shown below was a feature on the old times way of printing images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*wDmqKKJvSJbj9Xy2A9doIw.png" /><figcaption>Moiré pattern example (<a href="https://agostinhobritojr.github.io/tutorial/pdi/#fig_moire">source</a>: professor)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*7SwVrGz7-lWA70iN_L-r5g.jpeg" /><figcaption>DFT result (better implementation <a href="https://agostinhobritojr.github.io/tutorial/pdi/#fig_moire">here</a>)</figcaption></figure><p>The DFT result above is a little noisy, but good enough for understanding and usability. So, it’s possible to see symmetric groups of dots in the middle of the grey plan and those dots represent the periodic Moiré noise. Thus, it’s possible to use special filters to remove the dots, which if removed and done the inverse DFT it’s obtained a new and noiseless image.</p><h4>Homomorphic Filtering</h4><p>After this brief introduction to the concept, it’s proposed an implementation of the homomorphic filter using the DFT. This, being a way to improve lightning exposure on a picture with much shadows.</p><p>Every pixel of an image can be represented by an illuminance and reflectance components. The illuminance <em>i(x,y) </em>represents the amount of light upon the pixel, having slow variations through space. While that the reflectance <em>r(x, y) </em>indicates how much light is reflected. This component is strictly related to the material where the light it being reflected on and can have fast variations.</p><p>So, every pixel can be understood as being a mix of these two components:</p><blockquote>P(x, y) = i(x, y)r(x, y)</blockquote><p>This way, to fix the lighting on a scene it does not only take an increase to the illuminance component, since it is mixed with the reflectance; applying the DFT to the image we wouldn’t get the components separated.</p><p>The problem gets harder than this. Without much math, I present a summary to producing the image filtered:</p><blockquote>z(x, y) = ln(i(x, y)r(x, y)) = ln(i(x, y) + ln(r(x ,y))</blockquote><blockquote>S(u, v) = F(z(x ,y)). H(u, v)</blockquote><blockquote>s(x, y) = F−1(S(u, v))</blockquote><p>Being the H(u, v) the homomorphic filter in the frequency domain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*3Vq3SFbvANyrlZY9AJzQjg.png" /><figcaption>Homomorphic filter in the frequency domain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*DTeJuFQpuOnzsGVXyKlUqg.png" /><figcaption>Ideally YH (gamma high) and YL (gamma low) shouldn’t be the same or invert orders, so the filter can work.</figcaption></figure><p>where, from the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*KK6CkY_365F9E0LqeoSOmw.png" /></figure><p>The filtered image however then comes from:</p><blockquote>g(x, y) = exp(s(x, y))</blockquote><p>Furthermore, below the step by step is represented through a histogram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*TRRVEhPRdT5tom-9MFi15Q.png" /><figcaption>Homomorphic filter fluxogram (<a href="http://angelelouise.github.io/arquivos/pdi/lab8.html">source</a>)</figcaption></figure><p>Now I’m going to be explaining a little step by step to implementing the DFT for digital images; but first let’s remember how the coordinates for digital images are represented. On the part I introduction I mentioned that the (0,0) coordinate for digital images as being at the upper-left corner. If we DFT the image like that, the resulting image wouldn’t have the center on the image center. Thus, to helping this visualization and filter applications, it’s made what the figure below shows, so we have an image with the results centered on center. (Fourier plot for Moiré above is already like that).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*OS91iON-iQDMeJxQW7-3zA.png" /><figcaption>DFT showing (<a href="https://agostinhobritojr.github.io/tutorial/pdi/#fig_dftshift">Source</a>)</figcaption></figure><p>Although this technique implies a squared image, this process can be done by a built-in OpenCV function shown later. Now, another observation before implementation is that there are some optimizations related to the DFT calculation according to the image size. OpenCV affirms that multiples of two, three and five produce better results, so it’s also needed to recalculate the image size and most likely make a padding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dfba107e02f1b40bf64a52bbcc3e08b/href">https://medium.com/media/0dfba107e02f1b40bf64a52bbcc3e08b/href</a></iframe><p>To start things off let’s read a b&amp;w image with bad exposure to light, get its optimal DFT sizes and start some global variables needed to making usage of the filter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/801de39d042e6f101170feaac90ff681/href">https://medium.com/media/801de39d042e6f101170feaac90ff681/href</a></iframe><p>Now, having the ideal sizes we can make new borders sizes for the image, on the bottom and right (this can be done anyhow) with constant value. After the padding we can transform to the frequency domain and then make a shift mentioned earlier to be better represented (<a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_transforms/py_fourier_transform/py_fourier_transform.html">doc</a>). A more complex idea is the manipulation before showing the result, since we have values in the real and complex dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*XQeW1NW9m0TrPOwBtqV9Jw.jpeg" /><figcaption>Image chosen to apply the homomorphic filter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Aho3hihWj2HSaOMn7QhMrw.jpeg" /><figcaption>DFT for the image chosen</figcaption></figure><p>So, now with the image and the DFT in hands, it’s time to implement the filter itself. The code is commented according to the explanation before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba2c30390cc51c375760462a2184c29/href">https://medium.com/media/aba2c30390cc51c375760462a2184c29/href</a></iframe><p>The homomorphic function is then called by the functions responsible to changing its parameters as the user changes the trackbars. The trackbars were defined at the main function and take a limit, a function related to the bar and a variable corresponding to the actual value. The bars were by pattern maintained in the 0–100 scale and are responsible to change the parameters of the filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*h8yRE_zsTAww93DtoQwrYg.png" /><figcaption>Trackbars example</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/836b2dec7cc5aeb4e7f43e82548cfac6/href">https://medium.com/media/836b2dec7cc5aeb4e7f43e82548cfac6/href</a></iframe><p>The D0, C, YL and YH are sensible parameters that weren’t implemented to treat the user inputs with much precision, meaning that, are implemented for experiencing sake.</p><p>For all parameters, was not allowed to become 0 even if the user sets it so it doesn’t cancel its effect out. The C parameter was reduced in scale because was seen to be a lot more sensible to saturation than the others, and YL — YH, meaning gamma low and high respectively, were implemented so they are always one greater than the other.</p><p>The result after playing with the bars is a picture with a lot better light exposure, as expected. The black borders were the padding implemented to solve the optimization problem, not interfering on the filter calculus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Wh-5oPU-4gGbBz3X2r5CQw.png" /><figcaption>Homomorphic filter result</figcaption></figure><blockquote>That’s it, on this one saw more filtering and had some idea of the impact of the Fourier Transform for digital images. :)</blockquote><blockquote>Thank you for reading, to read more go:</blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-i-9fc72082f230?source=your_stories_page---------------------------">1. Introduction to OpenCV with Python</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-ii-6c5a12292587?source=your_stories_page---------------------------">2. Introduction to OpenCV with Python part II</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/lets-work-with-borders-opencv-implementation-in-python-b37c3d87c73a">4. Let’s play with image borders on OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/color-quantization-with-kmeans-in-opencv-99dbd0bde91b?source=your_stories_page---------------------------">5. Color quantization with Kmeans in OpenCV</a></blockquote><p>All the codes can be found at my public repository at <a href="https://github.com/elvisdias/Digital-Image-Processing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922a79cddf36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to OpenCV with python II]]></title>
            <link>https://medium.com/@elvisdias/introduction-to-opencv-with-python-ii-6c5a12292587?source=rss-1c41739d572f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c5a12292587</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Elvis Ferreira]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 19:09:25 GMT</pubDate>
            <atom:updated>2019-05-23T19:41:25.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to OpenCV with Python part II</h3><p>This is a second part tutorial introducing some basics of OpenCV with problems proposed by my digital image processing engineering class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIV5thp9FvDNsLcg9R7CqQ.png" /></figure><h3>Image histograms</h3><p>Histogram is a representative way of showing numerical data based on its distribution through a range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ysEKGfi4mwpVymlI.png" /><figcaption>Histogram example (source: <a href="https://en.wikipedia.org/wiki/Histogram">wikipedia</a>)</figcaption></figure><p>For images, a histogram represents how the pixels are distributed by its colors, giving a probabilistic idea of how frequent some color are in the image. Histograms can be used in automatic image segmentation, movement detection and granulometry, for example.</p><p>In openCV with python we have a bult-in function to do the job for us:</p><p><strong><em>cv2.calcHist([image], channels, mask, histSize, ranges[, hist[, accumulate]])</em></strong></p><ul><li>Image: Source image of type uint8 or float32. It is expected to be in square brackets.</li><li>Channels: Also given in square brackets, it’s the index of channel for which we calculate histogram. For example, if the input image is gray-scaled, its value is [0]. For color image, you can pass [0],[1] or [2] to calculate histogram of blue,green and red channel respectively.</li><li>Mask: To find a histogram of the full image we pass “None”, but if you want to calculate an histogram for a particular region its needed a mask image representing the region.</li><li>HistSize: Here we pass the bins. Bins basically stands for the blocks to represent the data plotted. Also given in square brackets, for full scale we pass [256].</li><li>Ranges: Range of the plot. Normally [0,256].</li></ul><p>For this tutorial we are going to be <a href="https://docs.opencv.org/3.1.0/d5/daf/tutorial_py_histogram_equalization.html">equalizing</a> the picture’s (gray-scaled) histogram. By that I mean to redistributes the<strong> </strong>image’s<strong> </strong>pixels<strong> </strong>intensity distributions in order to obtain a more stretched histogram of the picture. In summary it improves the image contrast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*1Y0kXW6V7240rLR6.png" /><figcaption>Histogram equalization (source: <a href="https://fr.mathworks.com/help/matlab/ref/matlab.graphics.chart.primitive.histogram.html">mathworks</a>)</figcaption></figure><p>In openCV we have a function also to make the equalization of an image, called <em>equalizeHist, </em>which has only the image to be equalized as parameter. So now, by calling the two functions on an image we can calculate the histogram for the original picture and then for the equalized one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3203dc0d81208c5133035085a0d11c45/href">https://medium.com/media/3203dc0d81208c5133035085a0d11c45/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*5YizverHqxFUD0S6XtMt4Q.jpeg" /><figcaption>Original Lenna gray-scaled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*bTENhVY9UB_mG59sC77bwQ.jpeg" /><figcaption>Lenna gray-scaled equalized</figcaption></figure><p>Proceeding into the code, we may want to see how the histograms look like for both pictures. The histogram calculation made by the function <em>calcHist() </em>does not return an image, instead it returns plottable data. For plotting the histograms we use the <em>matplotlib.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b2d83c9f2cb32b343b45a67a993cd7/href">https://medium.com/media/28b2d83c9f2cb32b343b45a67a993cd7/href</a></iframe><p>As a result we see how the pixels get more spread out through the range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pyPYHn4a7hNP4qyEkw0Siw.png" /><figcaption>Representation of the original histogram (blue) and the equalized histogram (red)</figcaption></figure><h3>Motion Detector with Histograms</h3><p>Let’s suppose now that we have a continuous capture of a scenario and we keep calculating the histogram for the frames. If the histogram changes it means something new showed up, if the new histogram is way different we can make assumptions or set an alarm.</p><p>Although we are going to be using the last program as a support, for this problem it’s going to be introduced the webcam function to capture images continuously. Likewise all functions used until now, openCV has a built-in class for this called <em>VideoCapture</em>. The object we create then can read frames from a camera, usually for tests the webcam.</p><p>To keep capturing the frames from the camera we are going loop over the camera read and consequently calculate its histograms. This is not an scalable way to do it, since we are processing too much frames, we could improve it to process one frame in four for example. Anyways, to make the problem easier it’s done in gray-scaled, converting the image from the camera using the openCV function <em>cvtColor</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3485ad006a777eac1d4375be67d049a8/href">https://medium.com/media/3485ad006a777eac1d4375be67d049a8/href</a></iframe><p>To compare the histograms was used the Chi-square distance, one of the distance measures that can be used as a measure of dissimilarity between two histograms. You don’t need to perfectly understand this concept, we are just worried in realizing changes in a determined scene, for this metric the less the result, the better the match of the two histograms (For a numerical example check the openCV <a href="https://docs.opencv.org/3.4/d8/dc8/tutorial_histogram_comparison.html">explanation</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*-XqnM-r0nZMNj-a-HDtHlw.png" /><figcaption>Chi-Square (source: <a href="https://docs.opencv.org/3.4/d8/dc8/tutorial_histogram_comparison.html">openCV</a>)</figcaption></figure><p>The numerical difference adopted was 2000, based on the openCV example that is not a drastic change but something clearly changed. So, if we get something bigger than 2000 on the difference, act!!! To get a visible change, was implemented a border change to all white. While the difference keep on bigger than the maximum determined, we have images with white borders shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/019acb3d71c0faa286d6f0b2d8785a5f/href">https://medium.com/media/019acb3d71c0faa286d6f0b2d8785a5f/href</a></iframe><p>It’s needed to release the camera object after done capturing, so the camera closes properly and won’t crash the execution.</p><h3>Digital Convolution and Filtering</h3><p>Let’s introduce now an important concept for when processing digital images: digital convolution. Digital convolution can be defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*nmQgtHUjpjoyC-Kc.png" /><figcaption>Digital convolution (source: <a href="https://docs.opencv.org/2.4.13.7/doc/tutorials/imgproc/imgtrans/filter_2d/filter_2d.html">openCV</a>)</figcaption></figure><p>being <em>I(x, y)</em> and <em>K(x, y)</em> the image and the kernel respectively. The kernel is a matrix usually composed of odd symmetrical dimensions (3x3, 5x5) and integer values. The values of the matrix will determine how the image will look like after the constitutional operation on the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*PjhkNqsrsIgNyRz9.jpg" /><figcaption>Kernel convolution (<a href="https://compvisionlab.wordpress.com/2013/04/07/convolution-opencv/">source</a>)</figcaption></figure><p>The image above describes well how the convolution works, the kernel chosen will be placed upon each pixel of the image and a summation of products between the matrices will become a single pixel value on the new image. The mask then keeps moving and calculating the new pixels until we have filled a whole new picture.</p><p>This process of convolution can be understood as filtering, with the kernels being filters. There are many existing established filters to different goals, such as borders detection, noise reduction, blur, etc.</p><p>Now, we are going to implement a python code to filter an image given some options to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e556086d682224990274f8882951faf/href">https://medium.com/media/0e556086d682224990274f8882951faf/href</a></iframe><p>The filters are defined as shown below besides the “gaussian laplacian”, which is going to be implemented by applying a filter on a filtered image as we will show further ahead. Yet, the values need the be defined as the type float due to the fact that the operations will face floating point numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1024584ffe8044598b615e05b602964d/href">https://medium.com/media/1024584ffe8044598b615e05b602964d/href</a></iframe><p>Some masks need to do some standard operations over the filters, while others don’t. Here we are going to show the mean mask being generated from an scale add between the mean filter multiplied by 1/9 and summed with an all zero matrix. The perks of each mask generation won’t be treated on this tutorial, only it’s usage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a3fc89b802ed7b74ff10f1df2564708/href">https://medium.com/media/8a3fc89b802ed7b74ff10f1df2564708/href</a></iframe><p>Now that we have a mask let’s start manipulating images. We are going to define a bool variable for the absolute filter, present the menu to the user and load a gray-scaled image for tests. The image has to be converted into a same type as the mask for the operation be possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf7dff78fc307c675ce6c69e5f0f0b37/href">https://medium.com/media/bf7dff78fc307c675ce6c69e5f0f0b37/href</a></iframe><p>Inside an infinite loop we can iterate over the picture loaded and choose which mask we will pass over the image. To get started we have already calculated the mean mask and set the absolute to True, so let’s start applying that and see the result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d001eeb4f5bb289bce059cd848bc336/href">https://medium.com/media/4d001eeb4f5bb289bce059cd848bc336/href</a></iframe><p>The openCV filter function <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html#void%20filter2D(InputArray%20src,%20OutputArray%20dst,%20int%20ddepth,%20InputArray%20kernel,%20Point%20anchor,%20double%20delta,%20int%20borderType)"><em>filter2D</em></a> is the responsible to passing the mask itself over the image. Setting the source image, the depth (-1 same as the source, usually the desired one), the mask and anchor [default value (-1,-1) means that the anchor is at the kernel center] is enough to get a new filtered image.</p><p>Transforming the matrix values from float to int to generate an image, we have as result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*5YizverHqxFUD0S6XtMt4Q.jpeg" /><figcaption>Lenna in B&amp;W with no filter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*v1xdjyHqb1rqMlZxn9KN-g.jpeg" /><figcaption>Lenna after mean mask and absolute</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52b8e8094b4fc6b64f41c84ae8de027c/href">https://medium.com/media/52b8e8094b4fc6b64f41c84ae8de027c/href</a></iframe><p>Now we have the option treatment for the user. The <em>waitKey</em> function now does not expect <em>any</em> key anymore, how it has been so far on the tutorials, it compares the key pressed to some result. Then, for each key we calculate a new mask to apply on the <em>filter2D</em> function. Using Lenna’s picture as usual, we find some interesting results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*P9YynBiVeQwmGEq-W3736g.png" /><figcaption>Vertical mask with abs (originally True)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*-6XoYpfgIe3djAdbrJ9z2A.png" /><figcaption>Vertical mask with no abs (Pressed “v” and “a”)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*DL3uZWPjy6Y0ByJ9cq6NAw.png" /><figcaption>Horizontal with abs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*-K_lk8xLzsvanrDOJThiWw.png" /><figcaption>Horizontal with no abs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*xL0ZU8I4MKWRXvmfS7HU9w.png" /><figcaption>Laplacian with abs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*O0ex7pDj1avYp-o-SrvCnQ.png" /><figcaption>Laplacian with no abs</figcaption></figure><p>Now to implement a combination of filters, called gaussian laplacian we first apply the gauss filter through the <em>filter2D </em>and call the variable mask to have the laplacian filter, so the next filter2D will apply it. This way we make sure the laplacian was done after the gauss.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42625c50b00567e90e1b04319a6779bd/href">https://medium.com/media/42625c50b00567e90e1b04319a6779bd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*wP4x6F_q3iGj_R9Xan9k4Q.png" /><figcaption>Gaussian Laplacian with abs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*uDnhPrDsVLBIpI-ZiMS3og.png" /><figcaption>Gaussian Laplacian with no abs</figcaption></figure><p>This examples used the Lenna picture but could have been done through the webcam how it was mentioned before. Here a quick adaptation to how it would be to make it more interesting applying the masks in real time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef187f6ab46621d27390135bdc9334fa/href">https://medium.com/media/ef187f6ab46621d27390135bdc9334fa/href</a></iframe><p>We would not need to call the Lenna picture before the loop only the camera object. Inside the loop we need then to read the frames and transform it to gray-scaled in float32 format. It’s done!! Just don’t forget to release the camera.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e92cee2d60693877872533eaaa2e4d0/href">https://medium.com/media/6e92cee2d60693877872533eaaa2e4d0/href</a></iframe><blockquote>That’s it, on this part I showed some work with image filtering and hopefully was convincing about its importance for image processing. :)</blockquote><blockquote>Thank you for reading, to read more go:</blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-i-9fc72082f230?source=your_stories_page---------------------------">1. Introduction to OpenCV with Python</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-fourier-transform-with-opencv-922a79cddf36">3. Lighting exposure improvement using Fourier Transform with OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/lets-work-with-borders-opencv-implementation-in-python-b37c3d87c73a">4. Let’s play with image borders on OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/color-quantization-with-kmeans-in-opencv-99dbd0bde91b?source=your_stories_page---------------------------">5. Color quantization with Kmeans in OpenCV</a></blockquote><p>All the codes can be found at my public repository at <a href="https://github.com/elvisdias/Digital-Image-Processing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c5a12292587" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to OpenCV with python I]]></title>
            <link>https://medium.com/@elvisdias/introduction-to-opencv-with-python-i-9fc72082f230?source=rss-1c41739d572f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fc72082f230</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Elvis Ferreira]]></dc:creator>
            <pubDate>Tue, 09 Apr 2019 17:01:15 GMT</pubDate>
            <atom:updated>2019-05-23T19:35:05.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to OpenCV with Python</h3><p>On this tutorial I am going to be showing solutions to some computer vision beginner level problems using the OpenCV library for Python. The problems here were proposed by my professor for an engineering Digital Image Processing class.</p><p>The OpenCV library is the most famous open source computer vision library (<a href="http://www.opencv.org/">http://www.opencv.org/</a>), available for many programming languages. With its immense amount of features we can make digital image modifications such as geometrical transformations, filtering, camera calibration, feature extraction, object detection, etc. The installation and set up used won’t be shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ymzYo_G8ZbNFyikY8x2RSg.png" /><figcaption><a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiC38yGnJniAhUAHbkGHWonDCUQjxx6BAgBEAI&amp;url=http%3A%2F%2Fvision.seecs.edu.pk%2Fats%2F&amp;psig=AOvVaw2fAxQDf5NfBt2755OkW4BI&amp;ust=1557861360037449">Source</a></figcaption></figure><h3>Pixels manipulation</h3><p>For the first problem, as a “hello world” type of problem, we will be accessing an image and manipulating its pixels.</p><p>First import the library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7141a5077a236bb7cc96f74945c31abd/href">https://medium.com/media/7141a5077a236bb7cc96f74945c31abd/href</a></iframe><p>To load an image, we use the function <em>imread</em> passing as parameters the name of the file to be read and how we want it to be read: 0 - Black and White, 1 - Color, -1 - Unchanged. For this problem we will be reading only as black and white and color. To show an image similarly as reading we call a function passing as parameter the name of the window to be shown and its content, usually the image object we create by calling <em>imread.</em></p><p>So, let’s read an image in black and white, access its pixels, change some and show the result. The images are loaded as a matrix (each element one pixel), if gray-scaled the matrix has two dimensions, with each element representing the intensity of gray. If colored, is a set of three matrices representing the color channels RGB.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27efad33df3adeaf86111616ec68d034/href">https://medium.com/media/27efad33df3adeaf86111616ec68d034/href</a></iframe><p><strong>Important note:</strong> in OpenCV the coordinates of the matrices are different. The horizontal coordinate is Y and the vertical X. Furthermore the upper corner left is where the (0, 0) origin is placed. So the coordinates grow from the upper corner left to the right and bottom directions. To make it easier to understand, hen looping over the coordinates using variables called X and Y we will only change to the OpenCV notation when accessing the position. Example further on this tutorial.</p><p>After read, we can do some easy matrix access and change the pixel color as we want. After modifying some, in a way to make a rectangle, to black we show the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*KOHx2dcE4GyEdmh8SrY0xw.png" /><figcaption>Original picture used for most part of the tutorials (<a href="https://en.wikipedia.org/wiki/Lenna">Lenna</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*OBkMaMvN37HYJiC5G87Pxg.jpeg" /></figure><p>A very useful command is necessary here so we can make multiple operations on images using the same code. The <em>waitKey</em> waits for the user to press a key to continue on the code (so we can see the result shown calmly). The parameter 0 waits for any key to be pressed to continue on the code. After this processing we then read again the image of Lenna but this time colored and make a red rectangle just as the black we did before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a9ca76b69db929376ef5c86300ff5fa/href">https://medium.com/media/5a9ca76b69db929376ef5c86300ff5fa/href</a></iframe><p>The pixels access is done differently for the colored images, the array we pass to the pixel represent the color channels in the BGR order (yes, it’s flipped for whatever reason). As output we have a maximum bright red rectangle, created at the same spot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*3hZSzxkY0IUd0Xgihqp_Yg.jpeg" /></figure><p>Finally to destroy the windows created for showing the images, we call the function <em>destroyAllWindows</em>, so nothing is shown after the program stops running.</p><p>Now, let’s make a rectangle with the negative of the b&amp;w image. The position of the rectangle is said by the user, and the negative effect is created subtracting the pixel from maximum possible value for the pixel (8 bit:255 here).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2e017d3c8e3868f58ba02c2f6487886/href">https://medium.com/media/c2e017d3c8e3868f58ba02c2f6487886/href</a></iframe><p>Running with the following coordinates 100, 200, 30, and 150 we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*lKVMYknBTkDyndLZ24Nt1g.jpeg" /></figure><p>Exploring even further pixel manipulation let’s reorder the four quadrants of the image inverted. A quadrant represents 1/4 of the image in a square format, as if the picture was cut in half vertically and horizontally.</p><p>For this challenge we are going to be using the numpy library to simplify the manipulation with matrix. The <em>numpy</em> function <em>split </em>splits the matrix in a given position and a given direction. After splitting the image we have to concatenate the parts in flipped order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d26e21d077d85148287b61f20006c719/href">https://medium.com/media/d26e21d077d85148287b61f20006c719/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*egbgeDcYarVrTa7aSt3ODw.jpeg" /></figure><h3>Filling regions</h3><p>In computer vision, one very usual task is counting objects in a detected scene. To perceive an object is necessary to detect the aggregation of pixels belonging to each object. To work better upon this, we are going to be using a binary picture (only gray-scaled pixels 0 and 255) meaning 0 the black background and 1 an object pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*s8j37nrWkOex4anMgorp7g.png" /><figcaption>Binary gray-scaled picture simulating objects</figcaption></figure><p>Here we assume that each aggregation of white pixels is a single object. So, a possible thing to do is labeling. Usually labeling algorithm has a binary image as input and returns a multi scaled gray image. For this purpose we are going to be using a built-in algorithm for filling regions called <em>floodfill</em>. This algorithm essentially searches, using a seed pixel as reference, for neighbors with the same color. If we give a color as parameter the function make all the pixels found by the search have that color.</p><p>The <em>floodFill </em>from opencv asks for the image, a mask (not used = None), the seed pixel and the color to color the seed and the similar neighbors. With that in hands we only need to go pixel by pixel checking its color, if it is white we change to some gray color, and then increment the gray color so the next object will have a different gray ton. As this process goes we can count how many times the <em>floodFill</em> was applied and assume that’s the number of objects we have in the scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29ce8cee5b97ec8cc07d4edab34cc9fd/href">https://medium.com/media/29ce8cee5b97ec8cc07d4edab34cc9fd/href</a></iframe><p>As a result we can’t see some objects because the gray scaled used was the same variable used to count the number of objects, so making it a very dark gray .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*g1OhDABTSi_Z47AsOtcwfA.jpeg" /><figcaption>Floodfill algorithm applied to a binary picture</figcaption></figure><p>Since we are using gray-scale to count the number of objects, we get limited by the value of 255 objects in a scene for a 8 bit processing. You can think of different ways of solving this problem, I’d suggest creating another variable that keeps track when the number of elements reaches 256 (starting from 0). When that happens this variable would be incremented and the <em>nelem </em>zeroed to start over. By the end of the labeling we would have objects with the same gray color but the variable that kept track together with <em>nelem </em>could do the math of how many more objects wore detected after the limit.</p><p>Now seeing the original binary picture again we can realize that there are two different type of objects, with a hole and without it. How could we count them separate?</p><p>First of all we don’t know if the ones cut by the border have the hole or not, so we ignore them (somehow). Having all the objects in scene, one way to solve this is applying <em>floodFill </em>in the background of the image to be white 255 (in case the scene had more than 255 objects we would have to edit the code to protect the max white from be used) so now we have the objects gray-scaled, the background white and the holes black (old background), since flood filling the background to white won’t hit the holes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a27057778cffe1b9cfc6bbe839e7989/href">https://medium.com/media/4a27057778cffe1b9cfc6bbe839e7989/href</a></iframe><p>With that in hands we solved to problem, having the holes black it’s just search for black pixels through the whole picture and for each black pixel found we increment the number of holes, and then flood fill it so we don’t get mistaken with the summation. For this example we do it with the same color of the background so we have the hole feeling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c24be9c0ecd5577f35574331df92d63/href">https://medium.com/media/0c24be9c0ecd5577f35574331df92d63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*i1nVQE9r-kViG2I1oJ0HFA.jpeg" /><figcaption>Output for couting holes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*krWhN_t53rrHrD0SMpsssA.png" /></figure><blockquote>That’s it, on this first part I tried to show some basics for understanding how a digital image is composed and how we can access its pixels and do some some analysis. I hope it was clear enough :)</blockquote><blockquote>Thank you for reading, to read more go:</blockquote><blockquote>2. <a href="https://medium.com/@elvisdias/introduction-to-opencv-with-python-ii-6c5a12292587">Introduction to OpenCV with Python part II</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/introduction-to-fourier-transform-with-opencv-922a79cddf36">3. Lighting exposure improvement using Fourier Transform with OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/lets-work-with-borders-opencv-implementation-in-python-b37c3d87c73a">4. Let’s play with image borders on OpenCV</a></blockquote><blockquote><a href="https://medium.com/@elvisdias/color-quantization-with-kmeans-in-opencv-99dbd0bde91b?source=your_stories_page---------------------------">5. Color quantization with Kmeans in OpenCV</a></blockquote><p>All the codes can be found at my public repository at <a href="https://github.com/elvisdias/Digital-Image-Processing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fc72082f230" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>