<?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 Yossefdawoad on Medium]]></title>
        <description><![CDATA[Stories by Yossefdawoad on Medium]]></description>
        <link>https://medium.com/@yossefdawoad15?source=rss-a0558c490019------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gexHTCnRD2gfjWZV</url>
            <title>Stories by Yossefdawoad on Medium</title>
            <link>https://medium.com/@yossefdawoad15?source=rss-a0558c490019------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:21:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yossefdawoad15/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[Tales of Concurrency & Parallelism in Dart, Part I: Async.]]></title>
            <link>https://medium.com/@yossefdawoad15/tales-of-concurrency-parallelism-in-dart-part-i-async-0251706b10b9?source=rss-a0558c490019------2</link>
            <guid isPermaLink="false">https://medium.com/p/0251706b10b9</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Yossefdawoad]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 19:36:50 GMT</pubDate>
            <atom:updated>2025-02-17T19:36:50.587Z</atom:updated>
            <content:encoded><![CDATA[<p>when building performant application in Dart or Flutter, you ‘ll encounter situation where you need to manage multiple tasks simultaneously. This is where you consider something like concurrency or ways of parallelizing your code, these where the <strong>async</strong> and <strong>threading (</strong>somewhat isolates) come into the picture. but what are the difference between these techniques, and how they work, do they achieve parallelization, Doesn’t Dart a single-threaded Language, all that and more, is what we will try to uncover in this article.</p><h3>Async: Efficient Single-Threaded Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8mEofMjCbqoP9cP0PhRJQ.jpeg" /><figcaption>one pizza cahier that efficiently execute orders from customers</figcaption></figure><p>Asynchronous programming allows you to execute multiple instructions (things) at the same time but never in parallel, how is this Possible?!! you might ask.</p><blockquote><strong>synchronous operation</strong>: A synchronous operation blocks other operations from executing until it completes, unlike an <strong>asynchronous operation</strong>.</blockquote><p>Let’s imagine This, you order a takeaway Pizza (Yummy!) the cashier makes the order and give you a recite <strong>While you wait your Order he move to the next Person and take another order, See What he did there </strong>(He Didn’t wait for Your Order to be Finished), he efficiently <strong>manage his time</strong> to execute the tasks required at the same time. THIS WHAT ASYNC ABOUT.</p><p>in programming terms instead of waiting for the API to return the result, or the File to be Completely read the by CPU (or rather the Event Loop — the cashier) can go and execute Something else and then return back to complete what it already starts it.</p><figure><img alt="An Image demonstrate Async tasks been initialized at the same time" src="https://cdn-images-1.medium.com/max/1024/1*sulCe7qgDRUuA8Q8vjTBcA.png" /><figcaption>An Image demonstrate Async tasks been initialized at the same time —image from <a href="https://bogas04.github.io/">Divjot Singh</a></figcaption></figure><h3>Basic Structure of Async Dart Code</h3><pre>// Future as return Type, and `async` keyword<br>Future&lt;T&gt; asyncFunction() async {<br>  // Perform some asynchronous operations<br>  // Use the await keyword to wait for a Future to complete<br>  T result = await someAsyncOperation();<br>  <br>  // Return the result<br>  return result;<br>}</pre><p>Let’s Break it Step by Step:</p><ul><li>we <strong>marked the function</strong> as <strong>async</strong> with the keyword async after the function parentheses as in asyncFunction() <strong><em>async</em></strong> {..}</li><li><strong>Returning</strong> Future or Future&lt;Type&gt; The asynchronous method usually returns <strong>Future&lt;Type&gt;</strong> where Type is the value Type that will eventually Returns, representing the eventual result of the operation.</li><li>Non-Blocking Asynchronous operations, usually indicated by the <strong>await</strong> keyword which mean I need pauses the execution of<strong> that function</strong> until the awaited Future is Completed then move to the next line, <strong>However, this doesn’t mean the CPU is idle during this time</strong> <strong>it’s free to execute other tasks to run maybe something else not in this function</strong> as an example, this seen in the code result = <strong>await </strong>someAsyncOperation()</li></ul><blockquote>NOTE</blockquote><blockquote>if we didn’t <strong>await</strong> the <strong><em>someAsyncOperation()</em></strong> the result would never be resolved the CPU only started the operation and never get chance for it to finish or another opportunity to get back to it, so be careful to <strong>await</strong> it, and for your knowledge the type of the result without the await keyword is The Future Type</blockquote><p>Now here is another dummy example before we get more Technical 🤓</p><pre>Future&lt;String&gt; fetchDataAsync() async {<br>  // Simulate a delay (e.g., waiting for a network response)<br>  await Future.delayed(Duration(seconds: 2));<br>  <br>  // Return some data<br>  return &quot;Data fetched!&quot;;<br>}<br><br>void main() async {<br>  // Call the async function and await its result<br>  String data = await fetchDataAsync();<br>  print(data); // Output: Data fetched!<br>}</pre><blockquote><strong>Tip</strong></blockquote><p>if your async function doesn’t return any, you can simply indicate that the return Type is Future&lt;void&gt; which mean Future of Type Void</p><p>Now Let’s spice things a bit, you are now working with Two Asynchronous methods</p><ul><li>fetchBiggestNumberAsync</li><li>fetchSmallestNumberAsync</li></ul><p>You want to <strong>call both of them</strong> within a single function called calculateMaxValue However, if you await each method sequentially, the code will run synchronously <em>(if every function takes like 5 sec you would wait 10 sec total)</em>. To solve this, consider using <strong>Future.wait([...])</strong> to handle them concurrently. This way, your code won’t get stuck waiting for each method to complete before moving on. 🚀</p><pre>Future&lt;int&gt; fetchBiggestNumberAsync() async {<br>    // Simulate a delay (e.g., waiting for a network response)<br>    await Future&lt;String&gt;.delayed(const Duration(seconds: 5));<br>    return double.inf;<br>}<br><br>Future&lt;List&gt; fetchSmallestNumberAsync() async {<br>    // Simulate a delay (e.g., waiting for a network response)<br>    await Future&lt;String&gt;.delayed(const Duration(seconds: 5));<br>    return - double.inf;<br>}<br><br>Future&lt;String&gt; calcluteMaxValue() async {<br><br>    // This code executes in 5 seconds instead of 10<br>    // (2 endpoints in parallel)<br>    var result = await Future.wait(<br>        [<br>            fetchBiggestNumberAsync(), <br>            fetchSmallestNumberAsync(),<br>        ],<br>    ); <br><br>    print(result); // [double.inf, - double.inf]<br>    return &#39;The winner is ${max(result)}&#39;;<br>}</pre><p>Future.wait([...]) Waits for multiple futures to complete and collects their results, The result should be<strong> list of all the values</strong> that were produced in<strong> the order that the futures are provided</strong></p><h3>Error Handling</h3><p>Asynchronous code must be treated with care, because its highly unsafe code meaning it can produce an error at any step, so we must take in consideration handling such unsafe cases.</p><p>Luckily for Us it’s as Simple as wrapping our code in try — catch Block</p><pre>try {<br>  print(&#39;Awaiting user order...&#39;);<br>  var order = await placePizzaOrderAsync();<br>  print(order);<br>} catch (err) {<br>  // handle the error case, what should be done here.<br>  print(&#39;Caught error: $err&#39;);<br>}</pre><p>this code will try to execute the async function placePizzaOrderAsync if the code unsuccessful it can be handled gracefully.</p><h3>Dart, the Nice Companion</h3><p>To catch common mistakes that arise while working with async and futures, Dart Recommend enabling the following Lints in your analysis_options.yaml file:</p><pre>linter:<br>  rules:<br>    discarded_futures: true<br>    unawaited_futures: true</pre><p>To Keep this manageable we talk about more advanced uses of async programming and will look into streams and maybe will touch on the parallel universes 😧 <strong>(Upcoming Part II)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0251706b10b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pyenv: Playing with Multiple Snakes on the same machine.]]></title>
            <link>https://medium.com/@yossefdawoad15/pyenv-playing-with-multiple-snakes-on-the-same-machine-44cf429551e7?source=rss-a0558c490019------2</link>
            <guid isPermaLink="false">https://medium.com/p/44cf429551e7</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yossefdawoad]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 21:16:45 GMT</pubDate>
            <atom:updated>2023-07-09T21:16:45.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_rQ_Tfika8o2okigpAs7A.jpeg" /><figcaption>multiple cute snakes come from inside pc, are these Snakes Leanardo.ai….!!!</figcaption></figure><p><strong>pyenv</strong> is by far one of simple python<strong> version management system</strong> you will ever use (once installed), but what does this even mean, that what we will talk about in this article.</p><h3>Introduction</h3><p>Python is a great programming language for many purposes, but sometimes you may need to use different versions of Python for different projects. For example, you may have a legacy project that runs on Python 2, but you also want to try out the latest features of Python 3.10. Or you may want to test your code on multiple Python versions to ensure compatibility and performance.</p><p>However, switching between different Python versions on your system is a complete hassle. You may run into<strong> conflicts</strong>,<strong> errors</strong>, or <strong>unexpected behaviors</strong>. You may also have to install and update each Python version separately, which can take up a lot of space and time and that where Python Version Management System come into the picture.</p><h4>What is Python Version Management System</h4><p>it’s the tool that allows you to install and switch between different versions of Python on your machine. make it so much useful when you need to work on projects that require different Python versions because some packages not up to date and not supporting newer versions of python, or if you want to try out new features of Python without affecting your installed system Python.</p><p>That’s where <strong>pyenv </strong>comes in, pyenv lets you easily <strong>install and manage</strong> multiple versions of Python, and also supports <strong>virtual environments</strong> for each version.</p><h3>How to install and use pyenv</h3><p>pyenv support <strong>macOS</strong> &amp; <strong>Linux</strong> natively by default, in the windows side the story a little bit different there are native port which called pyenv-win but it works like a charm.</p><p>there are different ways to install pyenv, depending on your operating system and preference. You can use <strong>Homebrew</strong> on macOS, a Windows installer, an automatic installer script, or a basic GitHub checkout. You can find the detailed instructions for each method on the<a href="https://github.com/pyenv/pyenv"> <strong>official documentation</strong></a>.</p><p>For this tutorial, I will use the automatic installer script, which works on most <strong>Unix-like systems</strong> (macOS &amp; Linux). To run the script, open your terminal and type:</p><pre>curl https://pyenv.run | bash</pre><p>This will download and run the script, which will clone the pyenv repository to ~/.pyenv and add some lines to your shell configuration file (such as ~/.bashrc or ~/.zshrc) to enable pyenv initialization.</p><p>After the installation is complete, you need to restart your shell or source your shell configuration file for the changes to take effect. You can do this by typing:</p><pre>exec &quot;$SHELL&quot;<br>#or this command<br>source ~/.bashrc</pre><p>For <strong>Windows system</strong> open your <strong>PowerShell </strong>and type:</p><pre>pip install pyenv-win --target $HOME\\.pyenv --upgrade</pre><p>If you run into an error with the above command, use the following instead :</p><pre>pip install pyenv-win --target $HOME\\.pyenv --no-user --upgrade</pre><p>the<strong> final step</strong> is add the <strong>pyenv </strong>command line tool to your path by running this in your power-shell:</p><pre>[System.Environment]::SetEnvironmentVariable(&#39;PYENV&#39;,$env:USERPROFILE + &quot;\.pyenv\pyenv-win\&quot;,&quot;User&quot;)<br>[System.Environment]::SetEnvironmentVariable(&#39;PYENV_HOME&#39;,$env:USERPROFILE + &quot;\.pyenv\pyenv-win\&quot;,&quot;User&quot;)<br>[System.Environment]::SetEnvironmentVariable(&#39;path&#39;, $env:USERPROFILE + &quot;\.pyenv\pyenv-win\bin;&quot; + $env:USERPROFILE + &quot;\.pyenv\pyenv-win\shims;&quot; + [System.Environment]::GetEnvironmentVariable(&#39;path&#39;, &quot;User&quot;),&quot;User&quot;)</pre><p>this Script Set the environment variables PYENV and PYENV_HOME that point to the installation folder, then add the bin folder to the PATH variable. Such that pyenv can be found when using the command line.</p><h3>Getting different snakes on our system</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2hUH6LroELmt1WgKKKTBw.png" /><figcaption>an image from penv doc display some commands of the tools</figcaption></figure><p>Now that you have pyenv installed, you can start installing different Python versions with it. To see the list of available Python versions, type:</p><pre>pyenv install --list</pre><p>You will see a long list of options, including official releases, development versions, Anaconda distributions, To install a specific Python version, type:</p><pre>pyenv install &lt;version&gt;</pre><p>where &lt;version&gt; is the name of the version you want to install. For example, to install Python 3.11.3 type:</p><pre>pyenv install 3.11.3</pre><p>This will download and compile the source code of the chosen Python version and install it under ~/.pyenv/versions. Depending on your system and network speed, this may take some time.</p><p>You can install as many Python versions as you want with pyenv. To see the list of installed Python versions, type:</p><pre>pyenv versions</pre><p>you will see somthing like this</p><pre>* system (set by /home/user/.pyenv/version)<br> 3.10.0<br> 3.9.9<br> 2.7.18</pre><p>The asterisk (*) indicates the current active Python version, which is the system Python by default. The (set by ...) part shows where the version is defined, which can be a global file, a local file, or an environment variable.</p><h3>Local install vs Global One</h3><p>So far what we installed on our system in <strong>global</strong> installation which mean the python versions we installed globally and can be accessed anywhere in our system, you Installed two different pythons Let&#39;s say3.10.0 and 3.11.3 how to switch between them, for example, to switch to Python 3.10.0 <strong>globally</strong>, type:</p><pre>pyenv global 3.10.0</pre><p>You can verify that the switch was successful by typing:</p><pre>python --version</pre><p>You can also use the pyenv <strong>local</strong> command, which sets the local Python version for the current directory and its subdirectories. This is useful when you want to use a different Python version for a specific project. For example, to set Python 2.7.18 as the local version for a project called legacy, type:</p><pre>cd lagacy/directory/<br>pyenv local 2.7</pre><p>This will create a file called .python-version in the legacy directory, which contains the name of the local Python version. You can check the local version by typing:</p><pre>pyenv local</pre><p>You should see the version you just installed in the directory.</p><p>But wait, <strong>there is more</strong>.</p><h3>Creating virtual environments with pyenv</h3><p>As mentioned earlier, pyenv also supports <strong>virtual environments</strong>, which are isolated environments that contain their own Python interpreter and packages. This allows you to create and manage different environments for each project and avoid conflicts or dependencies issues what is really special about this that you can tell pyenv what python version it should install for this environment you are creating.</p><p>Unfortunately, pyenv <strong>virtual Environment </strong>plugin as far as I know work on Unix-Like systems Like macOS and Linux and I don’t know a workaround for something like windows, if you do, please let me know in the comments.</p><p>To install it in your Unix-Like system, Type:</p><pre>$ git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv</pre><p>OPTIONAL — if you would like to add pyenv virtualenv-init to your shell to enable auto-activation of virtualenvs. This is entirely optional but pretty useful which will start the virtualenvs whenever you start your terminal.</p><pre>$ echo ‘eval “$(pyenv virtualenv-init -)”’ &gt;&gt; ~/.bashrc</pre><p>now <strong>restart </strong>your shell to enable pyenv-virtualenv.</p><p>To create virtual environments with pyenv, you need to install a plugin called pyenv-virtualenv, which is a wrapper around the built-in venv module or the third-party virtualenv package.</p><p>To install pyenv-virtualenv, follow the instructions on the official documentation right <a href="https://github.com/pyenv/pyenv-virtualenv">Here</a>.</p><p>After installing pyenv-virtualenv, you can create a new virtual environment by typing:</p><pre>pyenv virtualenv &lt;version&gt; &lt;name&gt;</pre><p>where <strong>&lt;version&gt;</strong> is the name of the Python version you want to use for the virtual environment, and<strong> &lt;name&gt;</strong> is the name of the virtual environment.</p><p>For example, to create a virtual environment called my_env using Python 3.10.0, type:</p><pre>pyenv virtualenv 3.10.0 my_env</pre><p>This will create a directory called my_env in ~/.pyenv/versions, which contains the Python interpreter and packages for the virtual environment.</p><p>To activate a virtual environment, you can use the pyenv activate command, which sets the current active Python version to the virtual environment and modifies your PATH accordingly.</p><p>For example, to <strong>activate</strong> my_env, type:</p><pre>pyenv activate my_env</pre><p>to deactivate my_env type:</p><pre>pyenv deactivate</pre><p>To delete a virtual environment, you can use the pyenv uninstall command, which removes the directory of the virtual environment from ~/.pyenv/versions.</p><p>For example, to delete my_env, type:</p><pre>pyenv uninstall my_env</pre><p>You will be prompted to confirm your choice before deleting.</p><h3>Conclusion</h3><p>In this article, I showed you how to install and use pyenv, a simple and powerful Python version management system that lets you easily install and switch between different versions of Python on your machine, and also create virtual environments for each version.</p><p>I hope you found this article helpful and learned something new about pyenv and Python.</p><figure><a href="https://www.buymeacoffee.com/yossefdawoad"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*34bci2J1uqOjofjHamBBSg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44cf429551e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Motion Detection on Esp32-Cam Board. Can you build your own Wireless Smart Cam for 10$..?!!!]]></title>
            <link>https://medium.com/@yossefdawoad15/motion-detection-on-esp32-cam-board-can-you-build-your-own-wireless-smart-cam-for-10-4b392514dd33?source=rss-a0558c490019------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b392514dd33</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[makers]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Yossefdawoad]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 23:07:10 GMT</pubDate>
            <atom:updated>2023-01-22T10:36:49.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Directional Motion Detection on The Cheap with just a 10$ Esp32-Cam Board.</h3><p>back in the days when i was doing my finals ( which is 4month ago ) i was interested in the esp32-cam board and wants to find it’s potential the project is simple can we reach somewhat an industry level smart camera with cheap board like esp32 (simple enough right..?) and whether or not if the esp32 capable of handling any computer vision task on the edge, and this my friend will be our journey so buckle up, because the result is interesting.</p><h3><strong>Motion detection</strong></h3><p>the most simple and smart camera out there advertises that it has in some way or anther a feature called <strong>motion detection</strong> so let’s define, <strong>motion detection</strong> is the process of detecting a change in the position of an object relative to its surroundings or the other way around like change in the surroundings relative to an object. It can be achieved by either mechanical or electronic methods or software. <strong>mouthful right so let’s break it down.</strong></p><p>the definition is divided the process to 2 main category:</p><ol><li>a change in the position of an object relative to its surroundings</li><li>a change in the surroundings relative to an object</li></ol><p>the first one is like focus on an object and preserve it’s position across the image or a scene, the second bit of the definition unlike the other one is observing the surroundings relative to an object in the scene, So our Job is Simple, detecting a change of objects position in the images to determine whether we detected if there motion or not</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8vf4-plmSwNo2fXF.jpg" /><figcaption>Source: <a href="https://www.tech-quantum.com/motion-detection-with-open-cv-and-csharp/">https://www.tech-quantum.com/motion-detection-with-open-cv-and-csharp/</a></figcaption></figure><h3><strong>A little bit about background subtraction</strong></h3><p>One of the popular ways to achieve a task like motion detection is an algorithm called<strong> Background subtraction</strong>, it is simple yet powerful and critical in many computer vision applications, it is a technique for separating foreground elements from the background which happen to be exactly what we need. This technique is used for detecting dynamically moving objects from static cameras. Background subtraction technique is important for motion detection or object tracking.</p><p>and Let me say that there are gazillion ways to perform motion detection and various others with libraries and tools like Open-CV Library and many other especially if you work with python environment. Some are very simple. And others are very complicated.</p><h3><strong>performing the task on the Esp32…Oh My. But Why ?</strong></h3><p>while we were planning for the project we take several consideration in doing it, the idea is simple make the Esp camera send the video feed to the server and then we can do whatever we like to process the video and everything else, but guess what it introduced a lot of headaches and complexity not in favor of what we want as the final product not to mention this approach done like hundred times and it come to mind what if the Esp32-CAM board acted as a stand alone surveillance camera and also perform the motion detection task, it is at-least the most basic feature a smart camera should have nowadays.</p><p>so we begun our experimentation that we will show in details at the end, (spoiler ahead) it was actually kinda possible with a bit of tweaking here and there we integrate a motion detection on our beloved esp32 and not only that we also can <strong>detect where that motion</strong> could be in the frame, pretty awesome right. and<strong> </strong>from this point lived happy after (actually there a lot lot stuff we did so let’s talk about ).</p><h3>THE ALGORITHM</h3><p>not to be afraid it turns out to be <strong>simple</strong> and really <strong>straight forward one</strong> so let’s tackle it a bit by bit</p><ol><li>We first acquire the image with the esp32, let’s imagine the image below is our image we want to process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*u-AuKQGq2BDpm0g4" /><figcaption>a 240 by 320 house image (image source: google)</figcaption></figure><p>2. Then take every four pixels of the image, averaging these four pixels so the output produced is a new scaled-down image like in the figure (each 4 pixels is now combined into one ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*3XUdbowwxAKWvEHs" /><figcaption>240x320 image scaled down by 4 to 60x80 (image source: google)</figcaption></figure><p>we have now scaled down image saving up a terminus computation power so we can begin processing the image relativity fast</p><p>3. Subtract each pixel from the previous frame(frame taken earlier and scaled down) and you get the difference between these two images, now let’s define a window called “motion view” (a List to store some values) It’s size defined by the width of our image, In our case it’s 80 values (so it’s array of 80 values and any value not a zero it indicate a movement in this portion of the image) by setting this value to one if there motion in this area of the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*vpg_vccvJgOxHgFB" /></figure><p>4. Now divide the window into 10 section, every section of these 10 contain 8 values (that will be used to determine easily where in the image the motion happened), the values of each section are 1 and 0, where the section that has the most ones is the section where the movement is the highest, because there was a great difference in this portion in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*5Cz_t14ryRJ0FZnM" /></figure><p>5. after knowing the highest movement section in the motion view (the one that has most of it’s values ones) we get it’s index that range from 0 to 9 (remember it’s 10 section) mapping 0 to 9 to a servo angle from 0 to 180 to move the camera into approximately the position of the movement.</p><p>6. Done, and you thought there would be a 6th step we all know great algorithm have five steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ckYz2s0MbJ2u78R" /><figcaption>yeah that me(hey me..!), and this a simple demo visualization of what is happening.</figcaption></figure><p>okay the theory is relativity simple... okay kinda (if it’s unclear yet please read it again, with focus mode activated ^_^)</p><p>Let’s Summarize real Quick before get the implementation, first get the image, down-sample the image, subtract each pixel from the previous frame taken by the camera, create array with the width of the down-sample image in our case it was 80 pixels (scaling down-sample the image just saved us a ton of computation nearly x6 time better performance), then we find where exactly the motion happened the most, point the servo motor towards this motion and pull the trigger…. wait what? the notification trigger yeah yeah indeed.</p><p>now fire up the <strong>Arduino IDE </strong>and lets get this real.</p><blockquote><strong>Note : make sure you installed ESP32 Board SDK in the Arduino IDE and Esp_pins.h file present in the same project folder.</strong></blockquote><p>first we include and declare the basic constant and variable that we will use in the entire program</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d3b64b02a8d7c1db96699786f03cca8/href">https://medium.com/media/3d3b64b02a8d7c1db96699786f03cca8/href</a></iframe><p>the setup function contain the initial setup or that code that will be executed once in the beginning of our program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4efcc07de2c32877b111568c0df61529/href">https://medium.com/media/4efcc07de2c32877b111568c0df61529/href</a></iframe><p>memset populate the motionView array with the value zero.</p><p>Now let’s get to the loop function then put define all mentioned function in the program (the functions used in each code segment so far will be explained later).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b7366778c3c78d8b7b5fa8e0a7bcf4d/href">https://medium.com/media/1b7366778c3c78d8b7b5fa8e0a7bcf4d/href</a></iframe><p>Now let’s see inside those magic function see what special about them setup_camera, capture_frame and isMotionDetected</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d8c24881d8b7ce5e5f6f9446237451/href">https://medium.com/media/b1d8c24881d8b7ce5e5f6f9446237451/href</a></iframe><p>the setup function initialize the esp32-cam with the specified configs, like JPEG quality, frame_size and most importantly pixel_format</p><p>First you must Know how the ESP Capture the image and store it because it’s different of you familiar to something like open-CV</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OVZ-Ag1R5MpGeD5thisbw.png" /><figcaption>image demonstrate how the esp32 image data stored</figcaption></figure><p>let’s continue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09f57e4c596dffe197df8908298d892/href">https://medium.com/media/d09f57e4c596dffe197df8908298d892/href</a></iframe><p>now capture_frame doing two things <strong>capture the next frame</strong> from the esp32 board and <strong>then down-sample</strong> the image (scale it down), nothing too hard so far (if you encounter an issue or you miss any thing feel free to mention in the comment and i will try update it with more detail) there is only one thing left isMotionDetection function which will be the core algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f6c37e8a4a2d3165d168582890108e3/href">https://medium.com/media/3f6c37e8a4a2d3165d168582890108e3/href</a></iframe><p>Now Connect the board with a servo motor connected to <strong>pin 14</strong>,if you try to move in front of the camera sensor you should see the servo moving toward the movement in real time HOW COOL IS THAT ….!!!!</p><h3>The Disadvantage of the approach</h3><p>surprisingly at first we expected noticeable lag or delay but thanks to this optimized way of doing motion detection it came pretty much usable but so you may ask what is the down size,</p><ul><li>First you obtain a black and white image to speed up the calculation which may not what you want for your project (technically a color image is possible but introduce a lot of complexity and i am not sure of the performance in the computation but it inter sting thing to expermint indeed)</li><li>second we obtain a raw image bytes instead of the JPEG encode image that Esp-Cam very optimized to capture and encode in real time which limit the speed of transferring an image-frame to a server for example to further process,</li></ul><p>if you love this kind of content let me know in the comments and follow me for more existing journey, i am planning to cover a ton of interesting other pieces that we experiment during our final project and other projects, that we previously done or planning to do in the future.</p><p>before i finish I should Mention and credit <a href="https://www.youtube.com/@MakersMashup">Makers Mashup</a> for his amazing video the one that point out the idea about the algorithm that explained in the article you should definitely check out his video and the content they make.</p><figure><a href="https://www.buymeacoffee.com/yossefdawoad"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><p>See You Good, Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b392514dd33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Green Screen Replacement like Movies-In Details (with python)]]></title>
            <link>https://medium.com/@yossefdawoad15/green-screen-replacement-like-movies-in-details-with-python-5eec7aeb36c6?source=rss-a0558c490019------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eec7aeb36c6</guid>
            <category><![CDATA[green-screen]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Yossefdawoad]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 20:57:14 GMT</pubDate>
            <atom:updated>2021-10-11T21:08:36.182Z</atom:updated>
            <content:encoded><![CDATA[<p>one of the first things you learn in computer vision is Most color and shape transformations are done just by mathematically operating on an image and changing it pixel-by-pixel.</p><p>with today’s tutorial, we will learn how we can use color transformation and thresholding only to create a “Green Screen Replacement”.</p><h3>What is The Image …?!</h3><p>the image simply can be represented by a grid of little squares called <strong>Pixels, </strong>the pixel describes the brightness of that area in the image. In the very simple image that is only black and white, we could think of each pixel as being represented by a 0 (for black) or 1 (white). Thus this image:</p><figure><img alt="simple black &amp; white grid of pixels" src="https://cdn-images-1.medium.com/max/881/1*uG3XQQWGiw2VlAnl4_Nkzg.png" /><figcaption>image from <a href="http://computerscience.chemeketa.edu/cs160Reader/DataRepresentation/ImageRepresentation.html">http://computerscience.chemeketa.edu/cs160Reader/DataRepresentation/ImageRepresentation.html</a></figcaption></figure><h3>Color Images</h3><p>but what about Color images, color images are interpreted as a 3D Matrix of values (width, height, depth )…!</p><p>The depth is the number of color channels. Most color images can be represented by combinations of only 3 colors: red, green, and blue values; these are known as RGB images. And for RGB images, the depth is 3.</p><p>Okay, we are ready for some practice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4519ff7cbf995ce9a038ff38d3995c17/href">https://medium.com/media/4519ff7cbf995ce9a038ff38d3995c17/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6esEOiCg1ZrGuEYN5Mzjg.jpeg" /></figure><p>We used OpenCV to read the image in our directory and then convert the image from BGR Color Space to RGB, But why is that?</p><p>in the old days when OpenCV was created this was the common format for camera manufacturers and image software providers, Now the Common format is RGB (Red, Green, Blue) and most of the modern software written accepts that format “RGB”.</p><h3>Green Screen Replacement just Like Movies …!</h3><p>we all seen at some point how movies make their effects and changing the background of their studios by just placing green background.</p><p>Let’s do some background masking with that image that we read above …!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d8bb46b41d6c510a6084f54db2ffb30/href">https://medium.com/media/1d8bb46b41d6c510a6084f54db2ffb30/href</a></iframe><p>what we did is defining a range that will detect all green colors from the image lower_range &amp;upper_range then apply the range to the image by creating a NumPy array first value for the Red color second for Green and the last for Blue value, and then we told python to place any pixel value to zero in the image except those in the mask area (which produce the image below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgGk0s3eWYkmakj4M1xZmQ.jpeg" /><figcaption>masked image where the green color replaced with white and other par of the image is just black</figcaption></figure><p>Now all things in the image that aren’t Green are just pure black.</p><p>Let’s Replace this white “Mask” area with a Space Background Image, shall we?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1fdfc1b664c55290c7f5b8d0ebb67c2/href">https://medium.com/media/d1fdfc1b664c55290c7f5b8d0ebb67c2/href</a></iframe><p>We read the background image then convert it to RGB, then resized the image to the same size as the previous image with .shape which returns the width and height of the image.</p><p>after resizing we do the opposite “setting the mask area to zero for the background image”, let’s revise why we do that? we blacken the green screen in the first and we left off just with the marvel hero “Thor” and the ground, for the background we do the opposite we blacken the ground and Thor and set their values to zero. now if we add them up the sky will be the background and thor will be in the foreground</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb5P6ppyL66vwaO8u1x5uw.jpeg" /></figure><p>whoa..!</p><p>I knew the image isn&#39;t perfect but this wasn&#39;t hard to get that result, but what we can do to enhance that noise and those green areas that didn’t detect? One thing we can run the code again with different sets of ranges to detect these small areas and apply the background again.</p><p>If you find this helpful just give it a like and expect a more powerful tutorial in the upcoming weeks. peace out ✌😍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eec7aeb36c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>