<?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 Sardor Abdirayimov on Medium]]></title>
        <description><![CDATA[Stories by Sardor Abdirayimov on Medium]]></description>
        <link>https://medium.com/@sardorabdirayimov?source=rss-153f1c1151ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eMJdOghiTCB5A151YDgFDw.jpeg</url>
            <title>Stories by Sardor Abdirayimov on Medium</title>
            <link>https://medium.com/@sardorabdirayimov?source=rss-153f1c1151ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:54:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sardorabdirayimov/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[[My Takeaways from Papers] Fooling DNNs]]></title>
            <link>https://medium.com/@sardorabdirayimov/my-takeaways-from-papers-fooling-dnns-e9d1706524e3?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9d1706524e3</guid>
            <category><![CDATA[fooling-dnn]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[adversaries]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 10:53:22 GMT</pubDate>
            <atom:updated>2023-08-09T10:53:22.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxvYD0wlRgowzZkLWYgMCw.png" /></figure><p>Let’s discover the important points from 2 papers about fooling DNNs</p><p>Hello all,</p><p>I hope you are doing well!</p><p>Last week, I was taking online course about <a href="https://www.coursera.org/learn/machine-learning-data-lifecycle-in-production/home/week/1">MLOps</a>. I truly enjoyed the course, but today’s topic is about fooling machine learning models. I came across with two amazing papers regarding manipulating (fooling) ML models with <strong><em>adversary examples</em></strong>. I loved both paper contents: <a href="https://arxiv.org/abs/1607.02533"><strong>[1607.02533] Adversarial examples in the physical world (arxiv.org)</strong></a><strong> </strong>and <a href="https://arxiv.org/abs/1412.6572"><strong>[1412.6572] Explaining and Harnessing Adversarial Examples (arxiv.org)</strong></a>.</p><blockquote><strong>Adversary example</strong> <em>means</em> <em>carefully crafted inputs that are slightly modified from regular data to exploit vulnerabilities in a machine learning model. For example, an image that looks normal to a human might be manipulated in a way that causes an AI image classifier to misclassify it.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0w2S-lZt4WEGVijfY4WJEQ.png" /></figure><blockquote>An adversarial example for the face recognition domain might consist of very subtle markings applied to a person’s face, so that a human observer would recognize their identity correctly, but a machine learning system would recognize them as being a different person.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzQ_uMenoBCk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzQ_uMenoBCk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzQ_uMenoBCk%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/a41ff1ab7249af3a365614ab413a07d4/href">https://medium.com/media/a41ff1ab7249af3a365614ab413a07d4/href</a></iframe><h3>Fast way to build adversarial images</h3><p>According to <a href="https://arxiv.org/abs/1607.02533">paper1</a>, one of the simplest methods to generate adversarial images, described in (<a href="https://arxiv.org/abs/1412.6572">Goodfellow et al., 2014</a>), is motivated by linearizing the cost function and solving for the perturbation that maximizes the cost subject to an L∞ constraint. This may be accomplished in closed form, for the cost of one call to back-propagation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Hs5Jjr5B709A4a2XxfgjLA.png" /></figure><p>In the formula above,</p><ul><li>ε: A small scalar value, representing the magnitude of perturbation.</li><li>∇_X J(θ, X, y): The gradient of the model’s cost function J with respect to the input image X, given model parameters θ and true label y.</li></ul><p>To sum up, I want to quote well-designed conclusion from <a href="https://arxiv.org/abs/1412.6572">paper2</a>:</p><blockquote>Gradient-based optimization is the workhorse of modern AI. Using a network that has been designed to be sufficiently linear–whether it is a ReLU or maxout network, an LSTM, or a sigmoid network that has been carefully configured not to saturate too much– we are able to fit most problems we care about, at least on the training set. The existence of adversarial examples suggests that being able to explain the training data or even being able to correctly label the test data does not imply that our models truly understand the tasks we have asked them to perform. Instead, their linear responses are overly confident at points that do not occur in the data distribution, and these confident predictions are often highly incorrect. This work has shown we can partially correct for this problem by explicitly identifying problematic points and correcting the model at each of these points. However, one may also conclude that the model families we use are intrinsically flawed. Ease of optimization has come at the cost of models that are easily misled. This motivates the development of optimization procedures that are able to train models whose behavior is more locally stable.</blockquote><p>Looking forward to hearing from you in comments!</p><p>Sincerely,</p><p><a href="https://medium.com/u/153f1c1151ed">Sardor Abdirayimov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9d1706524e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Paper Review] Towards ML Engineering — History of TFX]]></title>
            <link>https://medium.com/@sardorabdirayimov/paper-review-towards-ml-engineering-history-of-tfx-2d7102783b87?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7102783b87</guid>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[sibyl]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[tensorflow-extended]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 11:10:52 GMT</pubDate>
            <atom:updated>2023-08-08T11:10:52.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXF6EMK1McfemwTrkZ6AOw.png" /></figure><h3><strong>[My Takeaways from Paper]</strong> Towards ML Engineering — History of TFX</h3><h4>Lessons from 10+ years journey of ML Platform Evolution</h4><p><strong><em>This blog is perfect for:</em></strong><em> ML enthusiasts and students with basic knowledge of ML concepts</em></p><p>Machine Learning as a discipline has not achieved a descent level of maturity compared to Software Engineering. ML field is lacked the <strong>end-to-end platform</strong> for dynamic actions such as experimenting with data, model, preprocessing, tuning and etc. ML Engineering requires some level of automation to retrain or fine-tune the model based on changes of data in real world.</p><p>Previously, Google developed <a href="https://www.datanami.com/2014/07/17/inside-sibyl-googles-massively-parallel-machine-learning-platform/">Sibyl (2007–2020)</a> E2E ML Platform, which offered certain flexible ML workflows including Data Ingestion, Data Analysis and Validation, Training, Model Analysis and Training-Serving Skew Detection. However, the revolution of Deep Learning demanded Google to develop relevant framework. In 2015, Google announced <a href="https://www.tensorflow.org/">TensorFlow</a> — flexible framework to deal with DL models and inference. Later on, Google team understood that TensorFlow lacked a complete end-to-end production system, which Sibyl had. Google launched a platform offering flexibility of TensorFlow and end-to-end robustness of Sibyl under the name of <a href="https://www.tensorflow.org/tfx">TXF</a>. In another words, <a href="https://www.tensorflow.org/tfx">TFX</a> is a child of TensorFlow and Sibyl. <a href="https://www.tensorflow.org/tfx">TFX</a> was born in 2017. It has became publicly available since 2019.</p><h3>TFX Layers</h3><p>TFX has <a href="https://www.tensorflow.org/tfx/guide/examplegen"><strong>ExampleGen</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/statsgen"><strong>StatisticsGen</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/schemagen"><strong>SchemaGen</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/exampleval"><strong>ExampleValidator</strong></a> components to effectively deal with data management, analysis and validation.</p><p>TFX’s <a href="https://www.tensorflow.org/tfx/guide/evaluator"><strong>Evaluator</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/infra_validator"><strong>InfraValidator</strong></a> components makes ML Engineer life easy to validation and understanding of models.</p><p>TFX’s <a href="https://www.tensorflow.org/tfx/guide/examplegen"><strong>ExampleGen</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/transform"><strong>Transform</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/trainer"><strong>Trainer</strong></a>, <a href="https://www.tensorflow.org/tfx/guide/tuner"><strong>Tuner</strong></a> components, including TensorFlow Hub helps to deal with data caching, analyzer caching, warmstarting and transfer learning.</p><p>Combining such <a href="https://www.tensorflow.org/tfx">TFX</a> components makes easy to build robust and automated pipelines to operate in a dynamic environment.</p><p><a href="https://www.tensorflow.org/tfx">TFX</a> is designed to produce wide range of models that run on laptops, mobile and IoT, servers and even on browsers.</p><p>To conclude, <a href="https://www.tensorflow.org/tfx">TFX</a> is flexible and E2E Platform to bring AI Models to production and maintain these models with its components.</p><h4>Reference: <a href="https://arxiv.org/abs/2010.02013">[2010.02013] Towards ML Engineering: A Brief History Of TensorFlow Extended (TFX) (arxiv.org)</a></h4><p>Do not hesitate to follow me and share your insights after reading the paper above!</p><p>Sincerely,</p><p>By swimmer in the ocean of <strong>ML Engineering</strong> | <a href="https://medium.com/u/153f1c1151ed">Sardor Abdirayimov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7102783b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Awesome Lists” — the Ocean of great resources for everyone]]></title>
            <link>https://medium.com/@sardorabdirayimov/awesome-lists-the-ocean-of-great-resources-for-everyone-864f85c34af1?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/864f85c34af1</guid>
            <category><![CDATA[resources]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[awesome-list]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 16:02:10 GMT</pubDate>
            <atom:updated>2023-06-15T16:02:10.036Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Awesome Lists” — the Ocean of great resources for everyone</h3><p>Yes, Internet has a huge amount of information. When it comes to search something on the internet, first thing comes to my mind is Google search engine. I had developed an awkward stereotype. “<em>If Google does not have certain information about my request. It means that internet does not have that information”</em>. After discovering the GitHub, I killed this stereotypical mindset and understood that</p><blockquote>“Google Search Engine != Internet”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qbk75Dd6tDpup7fu" /></figure><h3>Awesome Lists on GitHub</h3><p>I still remember how I could find these <strong>awesome lists. </strong>It was early in this year. It was a long boring day of searching for the learning materials for deep learning. An interesting and fascinating list of resources appears on my screen. That list was well-written and designed in a very straightforward way to look up. I immediately check out the links of websites, and 90% of them indeed worked. I felt the different joy of my founding. It was even more joyful when I understood that the awesome lists are not limited to Deep Learning (AI) topics. I found an awesome list of books and hackathons (events). Also, GitHub community is very supportive. They keep updating the lists of relevant or necessary resources for many topics.</p><h3>To conclude,</h3><p>Awesome lists repository got around<strong> 260k stars</strong>, which shows how it is popular in the platform. I know you do not want to spend your valuable time for searching resources for hours. Awesome lists are great place to learn, stay up-to-date with cool resources!</p><p>Without saying any further words, here is the link to the Awesome Lists on GitHub:</p><p><a href="https://github.com/sindresorhus/awesome">sindresorhus/awesome: 😎 Awesome lists about all kinds of interesting topics (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=864f85c34af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation | Cheaper algorithm than you think]]></title>
            <link>https://medium.com/@sardorabdirayimov/backpropagation-cheaper-algorithm-than-you-think-4353610550b3?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4353610550b3</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[partial-derivative]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 15:50:05 GMT</pubDate>
            <atom:updated>2023-06-05T15:50:05.594Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Reader, I imagine backpropagation like a sweet secret sauce of “Neural Network” hamburger! Let&#39;s dive into the math and open the beauty of the Backpropagation!</em></p><p>The goal of backpropagation is to compute the partial derivatives <strong>∂C/∂w</strong> and <strong>∂C/∂b</strong> of the cost function <strong>C </strong>with respect to any weight <strong>w</strong> or bias <strong>b</strong> in the network. Backpropagation allows us to compute the partial derivatives <strong>∂Cx/∂w</strong> and <strong>∂Cx/∂b</strong> for a single training example. We then recover <strong>∂C/∂w</strong> and<strong> ∂C/∂b</strong> by averaging over training examples.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Algorithm of Backpropagation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxQM53QezdmWnTUx4Cmhgg.png" /></figure><p>Let’s assume that we have a neural network consisting of only input and output layers. In addition, the activation function is the multiplication of the input value and weight of the node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*CfSKyLAkU8WExKib8jyTIA.png" /></figure><p>After calculating the output of the activation function, we got 1.8. However, the actual (desired) output must be 0.9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*TWBLw5smrIDhki_qpkS1fA.png" /></figure><p>The cost(Loss) function here is MSE (Mean square Error).</p><h3>Going back to weights value</h3><p>The hottest part of the algorithm ♨️</p><p>In order to find the updated weights of the network, first we need to initialize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*SkwHfBuwvTbGNYc65-v8og.png" /></figure><ol><li>Learning rate (alpha). Usually, it is between 0.1–0.001. In our case, it is <strong><em>0.5</em></strong></li><li>Partial derivative <strong>∂C/∂w</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*90yWnQXotJoxM1RqZhLRig.png" /></figure><p>Based on our activation function the partial derivative functions would be in the following order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*-aXw8_R2ut9MpF1AWtFtng.png" /></figure><p>The gradient descent optimizer is ready to run on several epochs to find the optimal value for the weight of the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*Fe8YtHBLHvHB15v0x8Q4cA.png" /></figure><p>After iterating just <em>6</em> epochs (proving the computation efficiency), we got a weight value of<em> 1.6</em>. Which is closer to the target output of<em> 0.9</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*0hmTgCNol17cyAWfuxlZrg.png" /></figure><h3>Backpropagation Generalized to several layers</h3><p>The error from the output layer is used to compute the error at each preceding layer. This is done by recursively multiplying the transpose of the weight matrix with the error vector of the next layer and element-wise multiplying with the derivative of the activation function…</p><h3>Conclusion</h3><p>To sum up, we saw the simple implementation of backpropagation by using gradient descent to iteratively update the values of network weights from the output layer to the input layer.</p><p><em>Imagine a world where machines can learn, adapt, and make decisions just like humans. How do we enable such incredible capabilities? The answer lies in a revolutionary concept known as </em><strong><em>backpropagation</em></strong><em>.</em></p><p>P.S.: Comment below and share your thoughts about this amazing topic! 😃</p><p>My <strong>Lucid Charts (Graphs) </strong>used in the story: <a href="https://lucid.app/lucidchart/20973c64-6ba2-4cd5-9f6e-cc36fc489a6b/edit?view_items=sCx4SuJYp77f%2CLCx4LXwHemvU%2CLCx4I7rit.wD%2CgCx4ZEwramtz%2CcCx4_klYNKYi%2CsCx4RRPWsxlZ%2C.ix45dbp5d7a%2C.ix4sfBy2YVK%2C.ix4IBbW41yt%2C.ix48tLPvc-J%2C.ix4efOJSdtj%2Cjlx4r4cYwlCv%2Cqnx40CSCT8T2%2Crnx4oA_EdgLG%2Cjlx4nYiyQJNd&amp;invitationId=inv_934b13a4-1541-44c3-b6ce-e7f1223650d9">Click here</a></p><p>Reference:</p><ul><li><a href="http://neuralnetworksanddeeplearning.com/chap2.html">Neural networks and deep learning</a></li><li><a href="https://www.youtube.com/watch?v=khUVIZ3MON8">https://www.youtube.com/watch?v=khUVIZ3MON8</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4353610550b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring IPython: Beyond Python Interactivity | Part 1]]></title>
            <link>https://medium.com/@sardorabdirayimov/exproling-ipython-beyond-python-interactivity-part-1-4ac662667eaf?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac662667eaf</guid>
            <category><![CDATA[ipython]]></category>
            <category><![CDATA[interactive-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[secrets]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 05:43:05 GMT</pubDate>
            <atom:updated>2023-01-31T06:52:52.293Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The following suggestions will assist you in utilizing IPython’s features to the fullest. Do you frequently ask questions such as:</em></p><p><em>How do I invoke this function and what parameters and options does it have?</em></p><p><em>What does the code of this Python object look like?</em></p><p><em>What is contained in the imported package?</em></p><p><em>What properties or functions does this object possess?</em></p><p><em>If your answer is yes, then the current article is the perfect solution for you.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*og_ilRFpTVo3CX9D.png" /></figure><h3>Retrieving Documentation with❓</h3><p>Although some IDEs shows docstrings automatically, IPython allows you to show it manually by using <strong>?.</strong></p><pre>range?</pre><pre>Init signature: range(self, /, *args, **kwargs)<br>Docstring:     <br>range(stop) -&gt; range object<br>range(start, stop[, step]) -&gt; range object<br><br>Return an object that produces a sequence of integers from start (inclusive)<br>to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.<br>start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.<br>These are exactly the valid indices for a list of 4 elements.<br>When step is given, it specifies the increment (or decrement).<br>Type:           type<br>Subclasses: </pre><p><strong>This keyword can be used to completely anything in Python starting from built-in functions to classes. ✅✅✅</strong></p><pre>import numpy as np<br><br>a = 10<br>def display(x):<br>  &quot;&quot;&quot;displaying the variable&quot;&quot;&quot;<br>  print(x)<br>  return 1<br><br>np.arange?<br>print(&quot;---&quot;)<br>np?<br>print(&quot;---&quot;)<br>a?<br>print(&quot;---&quot;)<br>display?</pre><pre>Docstring:<br>arange([start,] stop[, step,], dtype=None, *, like=None)<br><br>Return evenly spaced values within a given interval.<br><br>Values are generated within the half-open interval ``[start, stop)``<br>(in other words, the interval including `start` but excluding `stop`).<br>For integer arguments the function is equivalent to the Python built-in<br>`range` function, but returns an ndarray rather than a list.<br><br>When using a non-integer step, such as 0.1, the results will often not<br>be consistent.  It is better to use `numpy.linspace` for these cases.<br>Type:      builtin_function_or_method<br>---<br>Type:        module<br>String form: &lt;module &#39;numpy&#39; from &#39;C:\\Users\\user\\anaconda3\\lib\\site-packages\\numpy\\__init__.py&#39;&gt;<br>File:        c:\users\user\anaconda3\lib\site-packages\numpy\__init__.py<br>Docstring:  <br>NumPy<br>=====<br><br>Provides<br>  1. An array object of arbitrary homogeneous items<br>  2. Fast mathematical operations over arrays<br>  3. Linear Algebra, Fourier Transforms, Random Number Generation<br>---<br>Type:        int<br>String form: 10<br>Docstring:  <br>int([x]) -&gt; integer<br>int(x, base=10) -&gt; integer<br><br>Convert a number or string to an integer, or return 0 if no arguments<br>are given.  If x is a number, return x.__int__().  For floating point<br>numbers, this truncates towards zero.<br><br>If x is not a number or if base is given, then x must be a string,<br>bytes, or bytearray instance representing an integer literal in the<br>given base.  The literal can be preceded by &#39;+&#39; or &#39;-&#39; and be surrounded<br>by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.<br>Base 0 means to interpret the base from the string as an integer literal.<br>&gt;&gt;&gt; int(&#39;0b100&#39;, base=0)<br>4<br>---<br>Signature: display(x)<br>Docstring: displaying the variable<br>File:      c:\users\user\appdata\local\temp\ipykernel_3856\789270433.py<br>Type:      function</pre><h3>Retrieving source code with ??</h3><p>The most amazing feature of IPython is the quick access to source code of the object. Note: Unfortunately, this command does not work with all libraries existing in Python world.</p><pre>from sklearn.model_selection import cross_val_score<br>cross_val_score??</pre><pre>Signature:<br>cross_val_score(<br>    estimator,<br>    X,<br>    y=None,<br>    *,<br>    groups=None,<br>    scoring=None,<br>    cv=None,<br>    n_jobs=None,<br>    verbose=0,<br>    fit_params=None,<br>    pre_dispatch=&#39;2*n_jobs&#39;,<br>    error_score=nan,<br>)<br>Source:   <br>def cross_val_score(<br>    estimator,<br>    X,<br>    y=None,<br>    *,<br>    groups=None,<br>    scoring=None,<br>    cv=None,<br>    n_jobs=None,<br>    verbose=0,<br>    fit_params=None,<br>    pre_dispatch=&quot;2*n_jobs&quot;,<br>    error_score=np.nan,<br>):<br>    # To ensure multimetric format is not supported<br>    scorer = check_scoring(estimator, scoring=scoring)<br><br>    cv_results = cross_validate(<br>        estimator=estimator,<br>        X=X,<br>        y=y,<br>        groups=groups,<br>        scoring={&quot;score&quot;: scorer},<br>        cv=cv,<br>        n_jobs=n_jobs,<br>        verbose=verbose,<br>        fit_params=fit_params,<br>        pre_dispatch=pre_dispatch,<br>        error_score=error_score,<br>    )<br>    return cv_results[&quot;test_score&quot;]<br>File:      c:\users\user\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py<br>Type:      function</pre><h3>&lt;Tab&gt; keyboard for code suggestions</h3><pre>from itertools import co&lt;TAB&gt;<br>###result of suggestion <br>combinations                   compress<br>combinations_with_replacement  count</pre><h3>Star(*) keyboard for Cool Usage</h3><p>Star(*) keyboard is synonym to word any(all)</p><pre>from pandas import * #importing all methods from pandas<br><br>import numpy as np<br>np.*ge? #look for all methods starting with anything and having the word `ge` between<br>#results<br>  np.arange<br>  np.average<br>  np.use_hugepage</pre><h3>In &amp; Out Objects</h3><p>The “In” and “Out” objects in IPython are lists that keep track of all the commands entered and executed in the IPython session in order, starting from 1.</p><pre>print(In)<br>In[0]*2<br>print(Out[-1])<br>print(Out)</pre><h3>Conclution:</h3><p>IPython has many hidden features which makes it perfect tool for data science. I hope features of IPython above will be super-handy for you in the future.</p><p>Keep an eye out for Parts 2 and 3 for even more IPython tips and tricks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac662667eaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Collection with Python and Telegram API via Telethon in inline bots]]></title>
            <link>https://medium.com/@sardorabdirayimov/image-collection-with-python-and-telegram-api-via-telethon-in-inline-bots-cf64c5ab092b?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf64c5ab092b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telethon]]></category>
            <category><![CDATA[automatic-image-gathering]]></category>
            <category><![CDATA[telegram-api]]></category>
            <category><![CDATA[image-collection]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Sat, 28 Jan 2023 23:25:10 GMT</pubDate>
            <atom:updated>2023-01-28T23:25:10.248Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a story about how to use a special tool called “Telethon” to collect pictures from Telegram inline bots. First, you need to get something called an API from Telegram. Then, you use a tool called “pip” to install Telethon. After that, you use a computer program to run Telethon and collect pictures that you want. This program uses your API to talk to Telegram and collect pictures. It saves the pictures in a folder on your computer so you can look at them later. This whole process is done in less than</em><strong><em> 5 minutes.</em></strong></p><p>Requirements from you:</p><ol><li>Basic knowledge of <strong>Python syntax</strong></li><li>Have a <strong>Telegram account</strong> to get(API_ID, API_HASH)</li></ol><h3>Step 1: Get API from my.telegram.com</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sfPWuoRd35Gx0xcoOF8VkQ.png" /></figure><h3>Step 2: Install Telethon:</h3><p>What is Telethon?</p><p><em>Telethon is a Python library that allows you to interact with the Telegram API. Telethon works by making requests to Telegram server via its API, Telegram API allows you to interact with the Telegram server using a series of methods, and Telethon wraps those methods in an easy-to-use Python library, you can use it to automate your Telegram account or create a bot, for example, you can use it to send messages, join/create groups, upload files and much more. In our case, we will get instant access to inline bot results.</em></p><pre>pip install telethon<br><br>#!pip install telethon</pre><h3>Step 3: Run Telethon Client</h3><pre>from telethon import TelegramClient<br><br><br>name=&quot;image_scrapper&quot;<br>api_id=111111 #get your own api_id from my.telegram.org<br>api_hash=a4a5defdse5f52fa #get your own api_hash from my.telegram.org<br>bot = &quot;pic&quot;<br>query = &quot;uzbek face&quot;<br>offset=0<br>async def save_img(results, offset):<br>    for index, result in enumerate(results):<br>        try:<br>            await result.download_media(f&quot;uzbek_face/img{offset}_{index}.png&quot;) #set the proper target location<br>            print(index)<br>        except Exception as e:<br>            print(index, e)<br><br>async with TelegramClient(name, api_id, api_hash) as client:<br>    for num in range(3): #in each iteration, client collects 30 images<br>        results = await client.inline_query(bot, query, offset=offset)<br>        await save_img(results, offset)<br>        offset = results.next_offset<br>        print(&quot;Done: &quot;, num)<br>        # print(results.__len__()) #30 object</pre><h3>How does it work?</h3><p>This code above is using the TelegramClient class from the Telethon library to interact with the Telegram API. It creates a new client object with the name “image_scrapper”, and uses the API ID and hash that you obtained from the Telegram website to authenticate the connection.</p><p>Then, it defines a function called save_img which takes in the results of an inline query and an offset, and saves each result as an image in a directory called &quot;uzbek_face&quot; with the file name in format of &quot;img{offset}_{index}.png&quot;.</p><p>It also starts an async with block and uses the client object to make an inline query to the Telegram server for the bot “pic” with the query “uzbek face”. It then uses the save_img function to download and save each result of the query as an image. The offset variable is used to keep track of which set of results have been already downloaded. The for loop in the end will repeat this process 3 times, and each time it will increase the offset by 1, so it will download 3*30 = 90 images in total, and prints &quot;Done: &quot; and the iteration number after each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OXXJhQQNQ7SuvsBwz868g.png" /></figure><h3>Supplementary:</h3><p>Youtube: <a href="https://www.youtube.com/watch?v=DmYNdc27fsQ&amp;t=205s">https://www.youtube.com/watch?v=DmYNdc27fsQ</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf64c5ab092b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Recognition in Python| FaceNet, MTCNN and SVM]]></title>
            <link>https://medium.com/@sardorabdirayimov/face-recognition-in-python-facenet-mtcnn-and-svm-80d0001a0469?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d0001a0469</guid>
            <category><![CDATA[facedetection]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[face-net]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 03:51:20 GMT</pubDate>
            <atom:updated>2022-12-29T03:51:20.039Z</atom:updated>
            <content:encoded><![CDATA[<p>Face Recognition is an interesting topic. It attracts even non-programmer people. Although 2022 AI technologies are further away complicated and interesting, this blog covers face recognition in python with Deep Learning models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxaXbPc3DQHEOMHN5XdxKQ.png" /></figure><ol><li>Collect images of individuals and create a folder:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*tH47FgAlwOa8Og5l0tpGUw.png" /></figure><p>2. Apply MTCNN model to extract face from image</p><p>3. Apply FaceNet model to get 1x1x512 array for each face</p><p>4. Train a simple SVM model to classify between 1x1x512 arrays</p><p>5. Save the model and the training data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*mM21jeA-6E2qehWUIOPtBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*lIgcBwp_O6DFH_tJM4QaRQ.png" /></figure><p>Detailed Video:</p><p><em>This video shows how I completed steps above and automated 2nd and 3rd steps in Python.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbG2tNYs7gw8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbG2tNYs7gw8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbG2tNYs7gw8%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/8e42e0ce8c5de6a5ed38202f3fff2e54/href">https://medium.com/media/8e42e0ce8c5de6a5ed38202f3fff2e54/href</a></iframe><p>6. Load SVM model and other models for real-time recognition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*FU4E_X4vok-QMPSXEo3ixA.png" /></figure><p>7. Implement all loaded models inside the While Loop</p><pre>import cv2 as cv<br>import numpy as np<br>import os<br>os.environ[&#39;TF_CPP_MIN_LOG_LEVEL&#39;]=&#39;2&#39;<br>from sklearn.preprocessing import LabelEncoder<br>import pickle<br>from keras_facenet import FaceNet<br><br>#INITIALIZE<br>facenet = FaceNet()<br>faces_embeddings = np.load(&quot;faces_embeddings_done_4classes.npz&quot;)<br>Y = faces_embeddings[&#39;arr_1&#39;]<br>encoder = LabelEncoder()<br>encoder.fit(Y)<br>haarcascade = cv.CascadeClassifier(&quot;haarcascade_frontalface_default.xml&quot;)<br>model = pickle.load(open(&quot;svm_model_160x160.pkl&quot;, &#39;rb&#39;))<br><br>cap = cv.VideoCapture(1)<br># WHILE LOOP<br><br>while cap.isOpened():<br>    _, frame = cap.read()<br>    rgb_img = cv.cvtColor(frame, cv.COLOR_BGR2RGB)<br>    gray_img = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)<br>    faces = haarcascade.detectMultiScale(gray_img, 1.3, 5)<br>    for x,y,w,h in faces:<br>        img = rgb_img[y:y+h, x:x+w]<br>        img = cv.resize(img, (160,160)) # 1x160x160x3<br>        img = np.expand_dims(img,axis=0)<br>        ypred = facenet.embeddings(img)<br>        face_name = model.predict(ypred)<br>        final_name = encoder.inverse_transform(face_name)[0]<br>        cv.rectangle(frame, (x,y), (x+w,y+h), (255,0,255), 10)<br>        cv.putText(frame, str(final_name), (x,y-10), cv.FONT_HERSHEY_SIMPLEX,<br>                   1, (0,0,255), 3, cv.LINE_AA)<br><br>    cv.imshow(&quot;Face Recognition:&quot;, frame)<br>    if cv.waitKey(1) &amp; ord(&#39;q&#39;) ==27:<br>        break<br><br>cap.release()<br>cv.destroyAllWindows</pre><p>Detailed video:</p><p>The following video teaches you how to load the models and basic cv2 library functions</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9niSMx2vxB4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9niSMx2vxB4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9niSMx2vxB4%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/0f2787f8b3d83466ab53608fa9707501/href">https://medium.com/media/0f2787f8b3d83466ab53608fa9707501/href</a></iframe><p>Source Code(GitHub): <a href="https://github.com/AbdirayimovS/face_recognition">AbdirayimovS/face_recognition (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d0001a0469" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Mask Detection | Image Classification on the custom dataset with TensorFlow, OpenCV and…]]></title>
            <link>https://medium.com/@sardorabdirayimov/face-mask-detection-image-classification-on-the-custom-dataset-with-tensorflow-opencv-and-f186b9a74c62?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/f186b9a74c62</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[vgg16]]></category>
            <category><![CDATA[face-mask-detection]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 01:44:24 GMT</pubDate>
            <atom:updated>2022-12-19T01:44:24.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Face Mask Detection | Image Classification on the custom dataset with TensorFlow, OpenCV and Mediapipe</h3><p><em>This blog will tell you how I created a face mask detection model on my custom dataset with 100 images. This project is ideally fit for beginners in Computer Vision and Deep Learning.</em></p><p>I created a dataset with help of a <a href="https://google.github.io/mediapipe/solutions/face_detection.html">mediapipe face detection model </a>to crop only my face image in the frame. I could collect 50 images with masks and 50 images without masks. Here is the Kaggle link to the dataset: <a href="https://www.kaggle.com/datasets/sardorabdirayimov/face-mask-images-100-images">Face Mask Images 100 images | Kaggle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC-1_d5hniRjlTfTZ3Fw1Q.png" /><figcaption>Train folder Images for both classes(0: No Mask; 1: Mask)</figcaption></figure><h3>Part 1: Used Jupyter Notebook to train model 🤖</h3><p>As a tradition, I imported all libraries in the first cell.</p><pre>import os <br>import tensorflow as tf<br>import math<br>import numpy as np <br>import matplotlib.pyplot as plt<br>from tensorflow import keras<br>from tensorflow.keras import layers<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.preprocessing import image_dataset_from_directory</pre><p>image_dataset_from_directory was used to read images and auto label them based on their folder names. IMG_SIZE is set to 128 due to vgg16-pre-trained model input limitation of 128x128 with 3 channels.</p><pre>IMG_SIZE=128<br>BATCH_SIZE=64<br>SEED=17<br>EPOCHS=10<br>TRAIN_DIR = &quot;mask_images/train&quot;<br>TEST_DIR = &quot;mask_images/test&quot;<br>VAL_DIR = &quot;mask_images/val&quot;<br><br>train_gen = image_dataset_from_directory(<br>    TRAIN_DIR,<br>    label_mode=&#39;binary&#39;,<br>    image_size=(IMG_SIZE,IMG_SIZE),<br>    batch_size=BATCH_SIZE,<br>    interpolation=&#39;nearest&#39;,<br>    labels=&#39;inferred&#39;, #i also do not know why i am adding them <br>    shuffle=True<br>)<br><br>test_gen = image_dataset_from_directory(<br>    TEST_DIR,<br>    image_size=(IMG_SIZE,IMG_SIZE),<br>    batch_size=BATCH_SIZE,<br>    shuffle=True,<br>    label_mode=&#39;binary&#39;,<br>    labels=&#39;inferred&#39;,<br>    interpolation=&#39;nearest&#39;)<br><br>val_gen = image_dataset_from_directory(<br>    VAL_DIR,<br>    image_size=(IMG_SIZE,IMG_SIZE),<br>    batch_size=BATCH_SIZE,<br>    shuffle=True,<br>    labels=&#39;inferred&#39;,<br>    label_mode=&#39;binary&#39;,<br>    interpolation=&#39;nearest&#39;<br>)</pre><p>Convert image data type to TensorFlow float 32 to decrease computational cost.</p><pre>def convert_to_float(image,label):<br>    image = tf.image.convert_image_dtype(image, dtype=tf.float32)<br>    return image,label<br><br><br>AUTOTUNE = tf.data.experimental.AUTOTUNE<br><br>ds_train = train_gen.map(convert_to_float).cache().prefetch(buffer_size=AUTOTUNE)<br>ds_val = test_gen.map(convert_to_float).cache().prefetch(buffer_size=AUTOTUNE)<br>ds_test = val_gen.map(convert_to_float).cache().prefetch(buffer_size=AUTOTUNE)</pre><p>Downloaded pre-trained model from Kaggle computer vision course`s dataset and imported it as the basement.</p><pre>pretrained_base = tf.keras.models.load_model(&quot;saved_models/vgg16-pretrained-base&quot;)<br>pretrained_base.trainable=False</pre><p>Created Sequential Model with pre-trained basement. The important thing to look at is the last Dense Layer with an activation function — sigmoid. As output, If my float result is higher than or equal to 0.5, then <strong>Mask detected</strong>, else — <strong>No Mask.</strong></p><pre>model=Sequential([<br>    pretrained_base,<br>    layers.Flatten(),<br>    layers.Dense(6, activation=&#39;relu&#39;),<br>    layers.Dense(1, activation=&#39;sigmoid&#39;)]) <br><br><br>model.compile(loss=&#39;binary_crossentropy&#39;,  <br>             optimizer=&#39;adam&#39;,<br>             metrics=[&#39;binary_accuracy&#39;])</pre><p>The training was quite fast and it required only 7 epochs to reach 100% accuracy in both the training and validation sets.</p><p>The evaluation part shows that model`s performance is very well.</p><p>After all tasks, I saved the model to load it in a .py file to run in a real-time experiment.</p><pre>history = model.fit(ds_train, epochs=EPOCHS, <br>                    validation_data=ds_val)<br><br>#OUTPUT Epoch 10/10<br>#2/2 [==============================] - 14s 3s/step - loss: 0.0391<br># binary_accuracy: 1.0000 <br># val_loss: 0.0219 - val_binary_accuracy: 1.0000<br><br>model.evaluate(ds_test, verbose=2)<br>model.evaluate(ds_val, verbose=2)<br><br>#Evaluation output<br>#<br>#1/1 - 2s - loss: 0.0389 - binary_accuracy: 1.0000 - 2s/epoch - 2s/step<br>#1/1 - 3s - loss: 0.0219 - binary_accuracy: 1.0000 - 3s/epoch - 3s/step<br><br>model.save(&#39;saved_models/my_model_v1&#39;) # saves entire model</pre><h3>Part 2: Used Python to run saved model in real-time</h3><p>First of all, I imported related libraries and configure the face detection model and OpenCV parameters. The Face Detection model by Mediapipe returns the normalized location of the face in the image, so I created a function to convert normalized coordinates to actual.</p><pre>import cv2 as cv<br>import mediapipe as mp<br>import math<br>import numpy as np<br>import tensorflow as tf<br><br>face_dt = mp.solutions.face_detection<br>mp_drawing = mp.solutions.drawing_utils<br>color = (0,255,0)<br>thickness = 2<br>mask_status=None<br>cap = cv.VideoCapture(0)<br><br>rect_start_point, rect_end_point = (0,0), (0,0)<br>facedet = face_dt.FaceDetection(model_selection=0,<br>                                min_detection_confidence=0.5)<br>saved_model = tf.keras.models.load_model(&quot;saved_models/my_model_kaggle_course_v3&quot;)<br><br>def normalized_to_pixel_coor( normalized_x, normalized_y, im_width, im_height):<br>    x_px = min(math.floor(normalized_x * im_width), im_width-1)<br>    y_px = min(math.floor(normalized_y * im_height), im_height-1)<br>  </pre><p>Basically, the Image goes through two models: the first model is Mediapipe face detection to get face location and the second model is our trained model to classify whether the face has a mask or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*ORA05jLChDZpBAJa2YkBVQ.png" /></figure><pre>while cap.isOpened():<br>    success, frame = cap.read()<br>    im_height, im_width,_ = frame.shape<br>    frame.flags.writeable = False<br>    image = cv.cvtColor(frame, cv.COLOR_BGR2RGB)<br>    results = facedet.process(image)<br>    frame.flags.writeable = True<br>    image = cv.cvtColor(image, cv.COLOR_RGB2BGR)<br>    if results.detections:<br>        for detection in results.detections:<br>            bd = detection.location_data.relative_bounding_box<br>            rect_start_point = normalized_to_pixel_coor(bd.xmin, bd.ymin, im_width, im_height)<br>            rect_end_point = normalized_to_pixel_coor(bd.xmin+bd.width, bd.ymin+bd.height, im_width, im_height)<br>            frame = cv.rectangle(image, rect_start_point,rect_end_point,color, thickness)<br><br>            ####prediction_part<br>            try:<br>                img = frame[rect_start_point[1]:rect_end_point[1],<br>                           rect_start_point[0]:rect_end_point[0]]<br>                img = cv.resize(img, (128, 128))<br>                img = np.array(img)<br>                final_face = tf.expand_dims(img, axis=0)<br>                ypred = saved_model.predict(final_face)<br>                if int(ypred[0]) ==0:<br>                    mask_status=&quot;Without Mask&quot;<br>                else:<br>                    mask_status=&quot;With Mask&quot;<br>                print(ypred)<br>                cv.putText(frame, mask_status, (50, 50),<br>                       cv.FONT_HERSHEY_SIMPLEX, 1, color, thickness,<br>                       cv.LINE_AA)<br>            except Exception as e:<br>                pass<br><br><br>    cv.imshow(&quot;Face Detection:&quot;, frame)<br>    if cv.waitKey(1) &amp; 0xFF == 27:<br>        break<br><br><br><br>cap.release()<br>cv.destroyAllWindows()</pre><h3>Conclusion</h3><p>To conclude, the project itself is interesting, especially the training on the custom dataset. I believe my limitation was having a small image set for the model to perform even better.</p><p>Youtube Link: <a href="https://youtu.be/OesKi_w3VxY">https://youtu.be/OesKi_w3VxY</a></p><p>Github Link : <a href="https://github.com/AbdirayimovS/FaceMaskClassification">AbdirayimovS/FaceMaskClassification: Transfer Learning model with pre-trained vgg16 model and custom_dataset (github.com)</a></p><p>Thank you for reading till the end. Feel free to share you thoughts in comment section 🙌✍️. Happy coming New Year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f186b9a74c62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Colors Detection using masks & contours in OpenCV]]></title>
            <link>https://medium.com/@sardorabdirayimov/colors-detection-using-masks-contours-in-opencv-72d127f0797e?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d127f0797e</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 11:35:56 GMT</pubDate>
            <atom:updated>2022-12-11T11:35:56.961Z</atom:updated>
            <content:encoded><![CDATA[<p>Let your computer<strong> detect</strong> four different colors in OpenCV 🔵🟢🟡🔴</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hijf5KGWQzMNmQIW4cm_qg.gif" /></figure><p>Welcome to the blog about how to detect different colors in OpenCV 📚</p><h3>Prepare objects with different colors</h3><p>In my case, I have these 4 colorful small circle objects. It may be your childhood toy, balloon, or even marker ✍️.</p><h3>Find the lower and upper boundaries of each color object</h3><p>Copy the code in the following article and play with it to find fixed `HSV` value ranges for specific colors.</p><p>Link: <a href="https://medium.com/@abdirayimovsardor20/lower-and-upper-mask-range-for-color-detection-opencv-7f64a5df568b">Lower and Upper Mask Range for Color Detection | by Sardor Abdirayimov | Dec, 2022 | Medium</a></p><p>I found 4 colors` lower and upper values for my camera and OS. It is a piece of cake! Just remember that there are no standard values for these color that fits each PC environment.</p><pre>colors = {&#39;blue&#39;: [np.array([95, 255, 85]), np.array([120, 255, 255])],<br>          &#39;red&#39;: [np.array([161, 165, 127]), np.array([178, 255, 255])],<br>          &#39;yellow&#39;: [np.array([16, 0, 99]), np.array([39, 255, 255])],<br>          &#39;green&#39;: [np.array([33, 19, 105]), np.array([77, 255, 255])]}</pre><h3>Call cv.inRange() and cv.findContours() for help</h3><p>cv.inRange() =&gt; In order to determine if the elements of a given array lie between the elements of two arrays representing upper bounds and lower bounds;</p><p>cv2.findContours() =&gt; finds the points where specifically, there is a significant difference noticed in the intensity of coloration. In our case, it looks for the difference in the image after applying cv.inRange() function.</p><h3>How does the Whole Algorithm work?</h3><p>Here is a step-by-step procedure of the whole algorithm. It is quite simple🤓</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pr8geugj0UHJCBow_T23Jg.png" /></figure><p>Whole Code: ✅</p><pre>import cv2 as cv<br>import numpy as np<br>import imutils<br><br><br>color = (255,255,255)<br># I have defined lower and upper boundaries for each color for my camera<br># Strongly recommended finding for your own camera.<br>colors = {&#39;blue&#39;: [np.array([95, 255, 85]), np.array([120, 255, 255])],<br>          &#39;red&#39;: [np.array([161, 165, 127]), np.array([178, 255, 255])],<br>          &#39;yellow&#39;: [np.array([16, 0, 99]), np.array([39, 255, 255])],<br>          &#39;green&#39;: [np.array([33, 19, 105]), np.array([77, 255, 255])]}<br><br><br>def find_color(frame, points):<br>    mask = cv.inRange(frame, points[0], points[1])#create mask with boundaries <br>    cnts = cv.findContours(mask, cv.RETR_TREE, <br>                           cv.CHAIN_APPROX_SIMPLE) # find contours from mask<br>    cnts = imutils.grab_contours(cnts)<br>    for c in cnts:<br>        area = cv.contourArea(c) # find how big countour is<br>        if area &gt; 5000:       # only if countour is big enough, then<br>            M = cv.moments(c)<br>            cx = int(M[&#39;m10&#39;] / M[&#39;m00&#39;]) # calculate X position<br>            cy = int(M[&#39;m01&#39;] / M[&#39;m00&#39;]) # calculate Y position<br>            return c, cx, cy<br><br>cap = cv.VideoCapture(0)<br><br>while cap.isOpened(): #main loop<br>    _, frame = cap.read()<br>    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) #convertion to HSV<br>    for name, clr in colors.items(): # for each color in colors<br>        if find_color(hsv, clr):  # call find_color function above<br>            c, cx, cy = find_color(hsv, clr)<br>            cv.drawContours(frame, [c], -1, color, 3) #draw contours<br>            cv.circle(frame, (cx, cy), 7, color, -1)  # draw circle<br>            cv.putText(frame, name, (cx,cy), <br>                        cv.FONT_HERSHEY_SIMPLEX, 1, color, 1) # put text<br>    cv.imshow(&quot;Frame: &quot;, frame) # show image<br>    if cv.waitKey(1) == ord(&#39;q&#39;):<br>        break<br><br>cap.release()   #idk what it is<br>cv.destroyAllWindows() # close all windows opened by opencv<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d127f0797e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lower and Upper  Mask Range for Color Detection | OpenCV]]></title>
            <link>https://medium.com/@sardorabdirayimov/lower-and-upper-mask-range-for-color-detection-opencv-7f64a5df568b?source=rss-153f1c1151ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f64a5df568b</guid>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[color-detection]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[hand-tools]]></category>
            <dc:creator><![CDATA[Sardor Abdirayimov]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 11:40:07 GMT</pubDate>
            <atom:updated>2022-12-03T11:40:07.304Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lower and Upper Mask Range for Color Detection</h3><p>Most of us have thought many times about color detection🔵🟢🔴. It sounds quite easy task to complete, isn`t it?</p><p>The built-in camera in my laptop is completely different from the web camera which I borrowed from the university. Lower and Upper mask ranges on the internet do not make sense to many cameras. Usually, lower and upper mask ranges for colors vary depending on camera quality and environmental conditions.</p><p>The most common algorithm for color detection is:</p><ol><li>Changing the COLOR format from BGR to HSV</li><li>Putting the MASK to the HSV image with lower and upper boundaries</li><li>Using `cv2.bitwise_and() ` to visualize only that particular color.</li></ol><h3>Big Issue | How to find Lower and Upper boundaries?</h3><p>Here is a handy solution with a GUI interface to find that particular boundary for a particular color in several tries.</p><p>For example, Here is the boundaries for a blue color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*poM9EVZXiDrNcq-kZB3V_w.png" /></figure><pre>import cv2 as cv<br>import numpy as np<br><br>Winname = &quot;Frame:&quot;<br><br>def nothing(x):<br>    pass<br><br>cv.namedWindow(&#39;Frame:&#39;)<br># H, S,V are for Lower Boundaries<br>#H2,S2,V2 are for Upper Boundaries<br>cv.createTrackbar(&#39;H&#39;,Winname,0,255,nothing)<br>cv.createTrackbar(&#39;S&#39;,Winname,0,255,nothing)<br>cv.createTrackbar(&#39;V&#39;,Winname,0,255,nothing)<br>cv.createTrackbar(&#39;H2&#39;,Winname,0,255,nothing)<br>cv.createTrackbar(&#39;S2&#39;,Winname,0,255,nothing)<br>cv.createTrackbar(&#39;V2&#39;,Winname,0,255,nothing)<br><br><br>cap = cv.VideoCapture(0)<br><br>while cap.isOpened():<br>    _, frame = cap.read()<br>    H = cv.getTrackbarPos(&#39;H&#39;, &#39;Frame:&#39;)<br>    S = cv.getTrackbarPos(&#39;S&#39;, &#39;Frame:&#39;)<br>    V = cv.getTrackbarPos(&#39;V&#39;, &#39;Frame:&#39;)<br>    H2 = cv.getTrackbarPos(&#39;H2&#39;, &#39;Frame:&#39;)<br>    S2 = cv.getTrackbarPos(&#39;S2&#39;, &#39;Frame:&#39;)<br>    V2 = cv.getTrackbarPos(&#39;V2&#39;, &#39;Frame:&#39;)<br>    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)<br>    lower_boundary = np.array([H, S, V])<br>    upper_boundary = np.array([H2,S2,V2])<br>    mask = cv.inRange(hsv, lower_boundary, upper_boundary)<br>    final = cv.bitwise_and(frame, frame, mask=mask)<br>    cv.imshow(&quot;Frame:&quot;, final)<br><br>    if cv.waitKey(1) == ord(&#39;q&#39;): break<br><br>cap.release()<br>cv.destroyAllWindows()</pre><p>This GUI program is super handy and saves tons of your time!</p><p>Feel free to write comments and share your thoughts. Sharing is Caring :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f64a5df568b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>