<?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 Dhruv Pandey on Medium]]></title>
        <description><![CDATA[Stories by Dhruv Pandey on Medium]]></description>
        <link>https://medium.com/@dhruv-pandey93?source=rss-ff2a7e9bdeda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uJMFD-FWhnC-ThUx4kzHlg.jpeg</url>
            <title>Stories by Dhruv Pandey on Medium</title>
            <link>https://medium.com/@dhruv-pandey93?source=rss-ff2a7e9bdeda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:25:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhruv-pandey93/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[A Password Manager That Fits in My Palm]]></title>
            <link>https://dhruv-pandey93.medium.com/a-password-manager-that-fits-in-my-palm-2d3e804bc020?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3e804bc020</guid>
            <category><![CDATA[password-management]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 08:23:47 GMT</pubDate>
            <atom:updated>2026-07-15T08:23:47.457Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I saw a <a href="https://www.youtube.com/shorts/cEonuWEmIlQ">shorts</a> that created a personal password manager/vault on a ESP-32 device. Striked me that every password manager I’ve ever used lives on someone else’s server. 1Password, LastPass — they all sync through the cloud. And while I trust these services for the most part, there’s always been this nagging thought at the back of my mind: <em>what if I could keep my passwords on a device I physically control?</em></p><p>Just a small, dedicated device that sits on my desk, stores my credentials encrypted, and lets me access them from any browser on my local network. So I built one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MEk9_0eHoj4wNi6plI9umg.jpeg" /><figcaption>Password vault on a ESP32-S3 Device</figcaption></figure><h3>The idea</h3><p>The concept is simple:</p><ul><li>A tiny ESP32-S3 board with a round AMOLED touchscreen holds all my passwords, encrypted with AES-256. I had this device lying from <a href="https://medium.com/@dhruv-pandey93/turn-by-turn-navigation-on-small-displays-9ea171474095?sharedUserId=dhruv-pandey93">my last project</a>, do check it out, its equally interesting!!</li><li>The device connects to my WiFi like any other gadget.</li><li>When I need a password, I open the device’s IP address in any browser — laptop, phone, whatever.</li><li>To authenticate, I type a 6-character code that’s displayed only on the physical screen and rotates every 60 seconds.</li><li>All the password management (adding, editing, deleting) happens in the browser. The device itself just shows a PIN pad, the password list, and the access key.</li></ul><p>No cloud. No accounts. No subscription. The passwords never leave my local network.</p><h3>How it works</h3><p>If you want to follow along with code, there is a <a href="https://github.com/pdhruv93/PasswordVault">Gihub repo for this project</a>.<br>Don’t worry, most of the parts was written/assited using AI, so you can also customize on top of it!</p><h4>Boot flow</h4><p>On first boot, the device doesn’t know your WiFi credentials. So it starts as a WiFi access point called <em>PasswordVault</em>. You connect to it from your phone, open <em>192.168.4.1</em>, and enter your WiFi SSID and password. One important thing — <em>it only supports 2.4GHz WiFi</em> (an ESP32 limitation). The device saves the credentials and reboots.</p><p>From then on, it connects to your WiFi automatically and gets an IP from your router. That IP is displayed on the round screen.</p><h4>The PIN</h4><p>The first thing you see after WiFi is configured is a PIN pad. First time, you set a 4-digit PIN. Every subsequent boot (or after the device auto-locks), you enter it again. The PIN is hashed with SHA-256 and stored on the device. It’s also used to derive the AES-256 encryption key for your vault.</p><h4>The rotating key</h4><p>This is the part I’m most happy with. When you want to access your passwords from a browser, you need to type a 6-character code that’s only visible on the physical AMOLED screen. This code changes every 60 seconds.</p><p>Why? Because even though my WiFi network is password-protected, I wanted an extra layer. Someone on my network can’t just open the device’s IP and see my passwords — they need to physically look at the device screen.</p><p>I deliberately excluded ambiguous characters (0/O, 1/I/L) from the key generation so you don’t squint at the tiny screen wondering if that’s a zero or an O.</p><h4>The browser UI</h4><p>Once you enter the key, you get a clean, dark-themed web interface. From here you can:<strong>View all</strong> saved credentials (passwords are masked by default, click to reveal), <strong>Add</strong> new entries with site, username, and password, <strong>Edit</strong> existing entries, <strong>Delete</strong> entries, <strong>Search</strong> across everything, <strong>Export</strong> your entire vault as a JSON backup file, <strong>Import</strong> a previously exported backup</p><p>The browser session persists across page refreshes — you don’t need to re-enter the key every time you reload the page. The session only dies when the device locks.</p><h4>Auto-lock</h4><p>After 50 seconds of no interaction (no touch on device screen, no API calls from any browser), the device:</p><p>1. Wipes all decrypted passwords from RAM</p><p>2. Kills all browser sessions</p><p>3. Returns to the PIN pad</p><p>If you’re mid-edit in the browser when this happens, it handles it gracefully — you’ll see a “Device is locked” message instead of a cryptic error.</p><h3>The technical bits</h3><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*b6v0UnBBJ2ssPAUgfpXqpg.png" /></figure><h4>Passwords survive firmware updates</h4><p>This was a concern I had early on — what happens when I update the firmware? Do I lose everything?</p><p>Turns out, no. The ESP32’s flash is divided into partitions. The firmware lives in the app partition, but all vault data (encrypted passwords, PIN hash, WiFi credentials) lives in the <em>NVS partition</em>. A normal Arduino IDE upload only overwrites the app partition. NVS stays untouched.</p><blockquote>One critical gotcha: Arduino IDE has a setting called “Erase All Flash Before Sketch Upload.” If you enable this, it nukes everything — including your passwords. Keep it disabled (it’s disabled by default).</blockquote><p>That said, I still recommend using the Export feature to download a backup before major firmware updates. Just in case.</p><h4>Security — honest assessment</h4><p>Let me be upfront about what this is and isn’t.</p><p><strong>What it does well:</strong></p><ul><li>Passwords are AES-256 encrypted at rest, using a key derived from your PIN</li><li>The rotating access key means someone on your network can’t just hit the IP and browse your passwords — they need physical access to the device screen</li><li>Auto-lock wipes all plaintext from RAM after 50 seconds of inactivity</li><li>Session tokens are random 32-character strings in HttpOnly cookies</li></ul><p><strong>What it doesn’t do:</strong></p><ul><li>No HTTPS — traffic between the browser and device is unencrypted HTTP. This is fine on a trusted home network, but I wouldn’t use this at a coffee shop.</li><li>The 4-digit PIN only has 10,000 combinations. But since you need physical access to the device to enter it, brute-forcing isn’t really practical.</li><li>WiFi credentials are stored in plaintext in NVS. This is standard for pretty much every IoT device.</li><li>The exported backup file is plaintext JSON — keep it secure.</li></ul><p>This isn’t meant to replace 1Password for your team at work. It’s a personal, offline, physical password vault for someone who wants to control where their credentials live.</p><h3>What’s next</h3><ul><li><strong>Battery support </strong>— the board has a LiPo battery header and a charging IC. With a small battery, this could be a truly portable device — pull it out of a drawer, unlock it, grab a password, and put it back. The AMOLED’s black background already helps with power efficiency, and the ESP32’s deep sleep could stretch battery life significantly.</li></ul><h3>Try it out</h3><p>The full source code is on <a href="https://github.com/pdhruv93/PasswordVault">GitHub</a>. If you build one, I’d love to hear about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*3afaF_9sxOejzXhEGbMRQw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MEk9_0eHoj4wNi6plI9umg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*lz7BnVb2W5Y0FD6wXnJdXw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Fq1q5DKl1k-BAnov046naw.jpeg" /><figcaption>ESP32-S3 device</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*8Gv9PPInOV9B2a8EhMvRgA.png" /><figcaption>Web interface</figcaption></figure><h3>Credits and inspiration</h3><p>I have to mention — the original spark for this project came from a YouTube Short by <a href="https://www.youtube.com/shorts/cEonuWEmIlQ">techiesms</a>. The implementation, code, and design decisions are mine (with a healthy amount of AI assistance, I’ll admit), but the idea of using a small ESP32 display as a password vault? That came from them.</p><p>These guys consistently put out really cool ESP32 and embedded projects. No sponsorship here, nothing paid — I just genuinely enjoy their content and feel it’s only right to credit the source that got me started. Go check out their channel if you’re into this kind of stuff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3e804bc020" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Economics of Water Purifiers: What AMCs Don’t Tell You]]></title>
            <link>https://dhruv-pandey93.medium.com/the-hidden-economics-of-water-purifiers-what-amcs-dont-tell-you-8e3183e836af?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3183e836af</guid>
            <category><![CDATA[water]]></category>
            <category><![CDATA[water-purifier]]></category>
            <category><![CDATA[scam]]></category>
            <category><![CDATA[consumer-protection]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 07:17:07 GMT</pubDate>
            <atom:updated>2026-02-12T07:17:07.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Real Business Behind Water Purifiers Isn’t the Machine</h3><p>When you buy a water purifier, you think you’re paying for clean drinking water for years to come. The machine itself feels like the main product.</p><p>But in reality, for most companies, the purifier is rarely where the real money is made. The profits come from <strong>maintenance contracts</strong> — what we all know as AMC (Annual Maintenance Contracts). Filters, membranes, periodic servicing, surprise replacements… that’s the long-term revenue stream.</p><p>It’s the classic <em>razor-and-blade</em> model: sell the razor once, and make money from the blades forever.</p><h3>Why I Started Digging Into This</h3><p>Drinking water today is completely commoditized. Almost every company promises “pure,” “healthy,” and “safe” water.</p><p>The bigger problem?<br>Even when you pay — sometimes a lot — you may still not get what you expect. There are conditions, fine print, and practices that most customers never fully understand.</p><p>I have an RO purifier from a reputed brand at home. I kept up with regular servicing, renewed AMCs on time, and did everything “by the book.”</p><p>Still, I kept facing doubts about water quality.</p><p>That curiosity pushed me to look deeper into how this industry actually works — from service visits to filter replacements — and what I discovered was… uncomfortable.</p><p>This article is my attempt to simplify those hidden mechanics so regular households can make more informed decisions.</p><h3>Catch #1: AMC Doesn’t Mean Everything Is Covered</h3><p>Every time you buy or renew an AMC, the company usually offers:</p><ul><li>One year of coverage</li><li>Free service visits</li><li>A “warranty” for the period</li></ul><p>Sounds reassuring, right?</p><p>Here’s the catch:<br>That warranty almost never applies to filters — unless explicitly written. It usually covers only electronic components.</p><p>Filters, membranes, carbon cartridges?<br>Those are considered <em>consumables</em>.</p><p>So even during AMC, if a filter is declared “expired,” you’re paying extra. Most customers don’t realize this distinction until they see the bill.</p><h3>Catch #2: The Warranty Window Game</h3><p>Whenever filters are replaced, they usually come with a short warranty — often around 90 days.</p><p>What many people experience is this:</p><ul><li>While the filter is under warranty, everything suddenly seems “fine.”</li><li>No faults.</li><li>No urgent replacements.</li><li>No warnings.</li></ul><p>But the moment the warranty expires? Suddenly:</p><ul><li>“Sir, this filter is very bad.”</li><li>“Your water is unsafe.”</li><li>“Membrane is failing.”</li><li>“You should change immediately.”</li></ul><p>Since this is about drinking water — and health — most people don’t argue. Fear kicks in. You trust the technician and approve replacements, even when they might not truly be necessary.</p><p>And that’s where the system quietly makes money.</p><h3>Catch #3: The Private-Service Shortcut</h3><p>Sometimes, a technician may casually offer:</p><blockquote><em>“Sir, outside company I can do this cheaper.”</em></blockquote><p>This is where the biggest margins often exist.</p><p>There are two possibilities here:</p><h4>Scenario 1: Duplicate or Refurbished Parts</h4><p>Cheap third-party filters and membranes are widely available in wholesale markets. These can be installed privately at lower cost — but quality and lifespan are questionable.</p><p>That part is obvious.</p><h4>Scenario 2: Genuine Parts… With a Twist</h4><p>This is the trickier one.</p><p>Some companies allow customers to verify spare parts online using serial numbers. So if the part is genuine, what’s the problem?</p><p>Here’s how it can go wrong.</p><p>When filters are still under warranty, companies replace them for free. A technician may convince a customer that their perfectly fine filter is faulty and swap it out. The customer doesn’t mind — it’s free.</p><p>But the removed filter, which still has life left in it, can later be reused in private jobs for other households.</p><p>It’s genuine — but not new.</p><p>As an end user, you can only verify the serial number. You can’t verify whether it was used earlier.</p><p>Another method is even more troubling:</p><ul><li>A technician ties up with a customer whose parts are still under warranty.</li><li>The customer raises a complaint to the company.</li><li>The company supplies a brand-new replacement part.</li><li>The technician never installs it.</li><li>He keeps the new part for a future private job.</li><li>The customer gets a small cut for cooperating.</li></ul><p>And here’s the uncomfortable truth: This practice is not limited to private jobs.</p><p>Partially used spare parts can unknowingly be installed in your machine even when you officially book a technician through the company. You might believe you’re safe because it’s a company visit — but the risk doesn’t automatically disappear.</p><p>Who is responsible here — the field technician alone, or something deeper in the system? I honestly don’t know. And that uncertainty is part of the problem.</p><h3>Catch #4: TDS Is Not the Whole Story</h3><p>Most service visits revolve around one number: <strong>TDS</strong>.</p><p>Technicians measure it, show you the meter, and conclude:</p><ul><li>“TDS is perfect, sir.”</li><li>Or: “TDS too high — filters must change.”</li></ul><p>But TDS alone does <strong>not</strong> define water safety.</p><p>It doesn’t tell you about:</p><ul><li>Microorganisms</li><li>Bacteria</li><li>Certain contaminants</li></ul><p>Parameters like pH, hardness, microbial presence, or chemical traces matter too — but those are rarely checked during routine visits.</p><p>To be fair, carrying lab-grade testing equipment for daily service calls isn’t practical. But as consumers, we shouldn’t assume a single number equals safe water.</p><h3>How to Be a Smarter Customer</h3><p>You can’t control the entire system — but you <em>can</em> reduce the chances of being taken for a ride.</p><h4>1. Understand Filter Life</h4><p>Filter lifespan depends heavily on your incoming water quality.</p><p>Check the TDS of your source water and research approximate filter replacement cycles for that range. Don’t replace just because someone says so — replace when it’s logically due.</p><h4>2. Keep a TDS Meter at Home</h4><p>TDS isn’t everything, but it’s a good early signal.</p><p>Also observe:</p><ul><li>Change in taste</li><li>Time taken to fill the tank</li><li>Amount of water going into the drain</li><li>Sudden drops or spikes in output TDS</li></ul><p>Patterns matter.</p><h4>3. Verify Spare Parts</h4><p>Make sure parts:</p><ul><li>Are factory-sealed</li><li>Have intact packaging</li><li>Can be verified on the company’s website</li><li>Even better: whenever possible, buy parts directly from the company instead of letting technicians source them independently.</li></ul><h4>4. Lab Testing Once a Year</h4><p>If you really want peace of mind, send your water sample to a certified lab annually.</p><p>It’s a small cost compared to your health — and it gives a full report across multiple parameters.</p><h3>Clean Water Deserves Clear Practices</h3><p>Most of us install water purifiers because we care about our families’ health. That trust shouldn’t be exploited through fear, vague warranties, or opaque servicing.</p><p>I’m not claiming every company or technician operates this way — but the structure of AMCs and consumables creates incentives that customers rarely see.</p><p>The more informed we are, the harder it becomes for anyone to misuse that trust.</p><p>Clean water is a necessity.<br> Transparency in how it’s delivered should be one too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3183e836af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn by turn Navigation on small displays]]></title>
            <link>https://dhruv-pandey93.medium.com/turn-by-turn-navigation-on-small-displays-9ea171474095?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ea171474095</guid>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[diy-projects]]></category>
            <category><![CDATA[automotive]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 18:04:56 GMT</pubDate>
            <atom:updated>2025-05-11T10:55:59.458Z</atom:updated>
            <content:encoded><![CDATA[<p>I barely drive my car without Google Maps or Waze, they have evolved so much but what I feel is still missing is the integration of these maps with small display devices.</p><p>I wanted to have bare minimum turn by turn navigation info on a small device(see the image for reference). This makes it a easy use-case to mount these small screen devices on bikes or e-scooters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*EWgTyKz2LgY0o82WgEp3Jw.png" /><figcaption>Image: Final implementation</figcaption></figure><h3>Current solutions in the market</h3><p>Just to be clear my solution is not trying to copy any existing solutions, its just a proof of concept that can be used to create better integrations in future.</p><p><a href="https://beeline.co/products/beeline-moto-ii"><strong>Beeline Moto</strong></a><br>This product is for bikes, perfect example of what I want to achieve. I really like their minimalist design and the navigation graphics, I would really like to try(if someone from Beeline is reading this, you know what to do).</p><p><a href="https://chronos.ke/"><strong>Chronos</strong></a><strong><br></strong>This is an open source solution, built using ESP32 device, has so many good customisations. The only thing you need to buy is a compatible ESP32 based display, and you are good to go. Only available for Android devices and the app is free, kudos to this guy!</p><h3>Motivation behind my idea</h3><p>In simple words, I want to mimic what Carplay and Android auto does. You start the navigation on your phone and keep it aside, the nav info is visible on the devices. I want similar solution(of-course with minimal navigation info) on small screen ESP-32 devices(because they are cheap).</p><h3>Current challenges</h3><p>Initially I felt it should be pretty much simple, but than I found Google Maps/Waze/Apple Maps app on the device never broadcast the navigation data to a third party device/app unless it supports Carplay or Android auto.<br>Thats not possible with small ESP32 devices.<br>There is a <em>hack</em>(which Gemini suggested) that on Android devices you could parse the Maps notifications by some third party app and then use this data in whatever way you want. iOS doesn’t allow that. Moreover does not seem reliable and a good proof of concept.</p><h3>My solution</h3><p>The<strong> </strong><em>best</em> way to achieve what I want is:<br>- Create a mobile app where the user initiates the navigation(like you do with Google maps or Waze).<br>- Inside the app listen to the manoeuver events(Turn right in 30meters). Broadcast this event to the ESP32 device over BLE.</p><h3>More challenges with my solution</h3><p>Things are not so easy and maybe thats why there doesn’t exist any solution yet 😢. The next couple of paras are my struggle, if you want feel free to skip.</p><p>For creating a mobile app where the user initiates navigation, I started with <a href="https://www.mapbox.com/">Mapbox</a>(cause their free plan looks generous). Since I am not a native app developer I wanted to go with React Native approach. But unfortunately there is no official React Native library to play with navigation. I found one <a href="https://www.npmjs.com/package/@pawan-pk/react-native-mapbox-navigation">unofficial library</a> but to my disappointment the library does not publish enough manoeuver data which only the core SDK does. If you see the <a href="https://github.com/pawan-pk/react-native-mapbox-navigation/blob/main/src/types.ts#L43">RouteProgress here</a> has less fields as compared to <a href="https://docs.mapbox.com/ios/navigation/api/3.8.1/navigation/documentation/mapboxnavigationcore/routeprogress/">official SDK lib</a>.<br><strong><em>If someone is a core iOS and Android app developer they might go this way and will work for sure</em></strong>, but it wasn’t for me.</p><p>Ultimately I had to go with <a href="https://www.npmjs.com/package/@googlemaps/react-native-navigation-sdk">Google Navigation SDK</a> which works and is the basis of my approach.</p><h3>Implementation</h3><p>Here is a <a href="https://github.com/pdhruv93/minimal-nav">link to the Github Repo</a> if you want to follow along. You can go through the Readme file for installations and setup, wont explain that here.</p><p>Google gives you their ultimate <a href="https://www.npmjs.com/package/@googlemaps/react-native-navigation-sdk">Navigation SDK</a> which you can use to build custom navigation solutions. As per their policy, you cannot recreate the Navigation solution as Google maps is intended for that. You can just do customisations with the Navigation. But this will work for us as we want to get the nav data, minimise the info and send it to ESP32 device.</p><p>The <a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/GuidedNavigation.tsx#L22">NavigationView</a> is the main component that displays the navigation view once you select the start and end points and start the navigation.</p><p>The <a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/useGuidedNavigation.ts">useGuidedNaviagtion</a> is the place where all the magic is happening:</p><ul><li>There is a <a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/useGuidedNavigation.ts#L81">helper which is called to start the navigation</a>.</li><li>The start location is <a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/useGuidedNavigation.ts#L16">user’s current location</a> and end location is entered by an <a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/GuidedNavigation.tsx#L25">autocomplete input</a>.</li><li>Enable the turn by turn direction event. Without this you won’t receive manoeuvre events and data.</li></ul><pre>navigationController.setTurnByTurnLoggingEnabled(true);</pre><ul><li>Start the navigation</li></ul><pre>navigationController.startGuidance();</pre><ul><li>The simulate option is just for testing sitting on my desk and not actually hit the roads to test.</li><li><a href="https://github.com/pdhruv93/minimal-nav/blob/main/guided-navigation/useGuidedNavigation.ts#L36">Create a callback to listen to manoeuvre event</a>(Turn right in 30m, take exit in 200m)</li></ul><p>Once you have the Manoeuvre data, whats left is to summarise/minimise the data and send it to BLE device. I am only sending the instruction(Turn left onto Some road), how much distance to take next step(in 300m), how much distance and time to reach destination and the <a href="https://developers.google.com/maps/documentation/navigation/ios-sdk/nav-only-feed#expandable-1">Manoeuvre images</a>.</p><p>The <a href="https://github.com/pdhruv93/minimal-nav/blob/main/ble-manager/index.ts">BLE helper class</a> is doing all the housekeeping work to connect to BLE server on ESP32 device and send data to the server over BLE.</p><h3>Showing Data on ESP32 Device</h3><p>I won’t go into much detail about the code. Will just provide reference to the code. <a href="https://github.com/pdhruv93/minimal-nav/tree/main/esp32-files">All code related to ESP32 is kept here.</a></p><ul><li><a href="https://www.waveshare.com/wiki/ESP32-S3-Touch-AMOLED-1.43">ESP32 Device from Waveshare</a></li><li><a href="https://github.com/pdhruv93/minimal-nav/blob/main/esp32-files/ESP32_Nav/ESP32_Nav.ino#L11-L64">Create a BLE server</a></li><li>Create LVGL ui using <a href="https://github.com/pdhruv93/minimal-nav/tree/main/esp32-files/Squareline_Project">Squareline studio project</a></li><li><a href="https://github.com/pdhruv93/minimal-nav/blob/main/esp32-files/ESP32_Nav/ESP32_Nav.ino#L51-L62">Extract values from BLE data and show on the UI</a></li></ul><p>If you are interested on working on this project feel free to reach me over email <em>dhruv.pandey93@gmail.com</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ERaieQ0u0A9rgV4cQyjkyQ.gif" /><figcaption>Final Implementation: React Native App+ESP32 device</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ea171474095" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Tuning using Keras Tuner]]></title>
            <link>https://medium.com/analytics-vidhya/hyperparameter-tuning-using-keras-tuner-72a8cb394d0f?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a8cb394d0f</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[keras-tuner]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 09:57:03 GMT</pubDate>
            <atom:updated>2021-07-05T06:32:12.114Z</atom:updated>
            <content:encoded><![CDATA[<p>The most critical part of any Deep Learning model is finding the values of hyperparameters that would result in a model with high accuracy.</p><p>Learning Rate, Batch size, number of neurons in a layer are some common examples of model hyperparameters. <a href="https://medium.com/analytics-vidhya/deep-learning-the-summarized-way-part-1-23e2eee01ddd">Check my article</a> to know more about hyperparameters and what is the difference between model parameters and hyperparameters.</p><h3>How does the manual process of tuning works?</h3><p>For performing hyperparameter tuning, you start with some initial values assigned to your hyperparameters(with experience, you will be able to figure out some good starting values). Once the rough values are assigned, you train your model, and based on the accuracy and loss results, you tweak the model hyperparameters. You repeat this process manually until you find that the model accuracy is high.</p><h3>So how can we make this simple?</h3><p>The above process is very time-consuming and frankly speaking, is a bit annoying. That&#39;s where “<strong><em>Keras Tuner</em></strong>” comes into the picture, a utility provided by Keras to handle all this cumbersome process by itself.</p><p>The Tuner expects the user to provide certain values for each hyperparameter. Suppose the user wants to experiment Learning rate with values 0.1, 0.05, 0.5, and the number of nodes in the first layer with values 16, 32, 64. So the tuner will create a combination of (0.1, 16), (0.1, 32), (0.1, 64), (0.05, 16)… and then try to find the model performance for each combination. Once all the combinations and trials are completed the Tuner prints out the parameter values that gave the best performance. How Tuner creates this combination is based on the strategy that we ask Tuner to select(Grid Search or Randomized or Bayesian ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*UtLOPN6bA3PJz7AlnAb1fQ.png" /><figcaption>How Tuner creates a combination of values for different hyperparameter. The dots represent a particular combination of hyperparameter values. Left Image: Grid Search, Right Image: Random Search [Image <a href="https://fiennyangeln.github.io/papers/docs/hyperparameter-tuning/">Source Link</a>]</figcaption></figure><blockquote>As a user, you just need to define a set of values for your hyperparameters and give it to Tuner and the utility will come up with the best combination of hyperparameters that you need to use to get a model with high accuracy.</blockquote><p>Note that the utility will not create the model architecture for you, it will just find the optimal hyperparameter values for a given model(that it takes as input). Also, note that as you increase Tuner parameters the possible combinations increase, resulting in an increase in tuning time. <em>So choose wisely which parameters you want to tune.</em></p><h3>How it&#39;s done?</h3><p>As with all of my articles, I will explain Tuner utility with sample code from <a href="https://www.kaggle.com/pdhruv93/fire-detector">my notebook on Kaggle</a>. Please check the notebook to follow along.</p><p>The first section marks the necessary imports followed by some global variable declarations. A new and important declaration here is <em>EARLY_STOPPING_PATIENCE </em>which signifies that if the accuracy does not increase after these many epochs Tuner will break the current trial and continue with the next to save resources. The next section “Making ImageDataGenerator compatible directory” is not related to Tuner and is used to make the dataset compatible with the ImageDataGenerator. We import our datasets, apply augmentation in the next section, so nothing fancy there.</p><p>Then comes the main part where we define the model architecture, I will call this Step1.</p><h3>Step1: Define model architecture</h3><p>We define a custom function where we construct our model architecture by parameterizing the model hyperparameters that we want to tune. The code for constructing the model architecture remains pretty much the same as earlier except that any hyperparameter(that you wish to tune) is treated as a <em>Tuner variable.</em></p><p>Suppose we want to tune the number of filters in a Conv2D layer, here is how traditional code would look like:</p><pre>model.add(Conv2D(32 ,(3, 3), padding=&quot;same&quot;, input_shape=(128, 128, 3)))</pre><p>Notice we have explicitly defined 32 as the number of filters in this layer. Using Tuner we can parameterize this variable. This is how the code will look:</p><pre>model.add(Conv2D(tuner.Int(&quot;conv1&quot;, min_value=32, max_value=96, step=32),(3, 3), padding=&quot;same&quot;, input_shape=(128, 128, 3)))</pre><p>We replaced 32 with expression tuner.Int(“conv1”, min_value=32, max_value=96, step=32).</p><p>conv1 is the name of the variable that we have used to represent this hyperparameter(number of filters in this layer). The range of values that we are allowing for this hyperparameter is [32, 96] and step of 32.</p><p>Let’s see another example. We want to tune the Learning rate for the model. This is how we would write the traditional code:</p><pre>lr = 0.1</pre><p>This is how we will use the Tuner object for this variable:</p><pre>lr = tuner.Choice(&quot;learning_rate&quot;, values=[1e-1, 1e-2, 1e-3])</pre><p>This way we can parameterize our model hyperparameters and construct the model. This model is then passed to the Tuner object(next step) for finding the best set of hyperparameters.</p><h3>Step2: Create Tuner Object</h3><p>We create a model object and pass the <em>build_model</em>(the function that we created above). Every time you run a deep learning model, the initializations and updates are random. So<em> seed</em> value allows some constant start point for the model. The directory is the output directory that Tuner uses to generate any temp files or some storage.</p><pre>tuner = kt.Hyperband(build_model, objective=&quot;val_accuracy&quot;, max_epochs=EPOCHS, factor=3, seed=42, directory=&#39;./&#39;, project_name=&#39;my_hyperband_tuner&#39;)</pre><p>The important thing to note here is the <em>kt.Hyperband. </em>This is the combination strategy that we want Tuner to use. I have already described the combination strategy in short above. Other options are <em>kt.RandomSearch, kt.BayesianOptimization</em> but I will not go into more details about these in this article.</p><h3>Step3: Search the best hyperparameters</h3><p>The final and fun part comes where the Tuner utility starts searching for the optimal values for the hyperparameters. This is how you start the search:</p><pre>tuner.search(train_generator, validation_data=test_generator, batch_size=BATCH_SIZE, callbacks=[earlyStopper], epochs=EPOCHS)</pre><p>The <em>earlyStopper </em>callback is responsible to break the execution of the current trial if the accuracy did not increase after certain epochs. This is how you can define the callback:</p><pre>earlyStopper = EarlyStopping(monitor=&quot;val_loss&quot;, patience=EARLY_STOPPING_PATIENCE, restore_best_weights=True)</pre><p>We already declared <em>EARLY_STOPPING_PATIENCE</em> in the global variables.</p><h3>Output</h3><p>Once the search has started, the Tuner will create combinations of the hyperparameter values based on the defined strategy. There would be multiple trials(I could not find out a way to check how many trials would be there). The entire process is automated and nothing is expected from you during this process but it takes a lot of time for this search process to get completed, so sit patiently and let it complete.</p><p>Here is a sample output of the search process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*_nGQYyMj0Pynj311CTNKLQ.png" /><figcaption>Sample Output during the search process</figcaption></figure><blockquote>You will notice that the optimal values for certain hyperparameters would be nearly the same in all the trials. For example, if you opted to try 0.1, 0.01, 0.05 for the Learning Rate, and you notice that the optimal value is always 0.1 for all the trials, I recommend stopping the search process and removing the other values for the Learning Rate. This is because the other values(0.01, 0.05) are unnecessarily increasing the combinations during search process and hence are increasing the search time.</blockquote><p>Once the search process is completed and you get the optimal values of the hyperparameters, you can create the model using these final values and expect a good-performing model.</p><h3>Final Words</h3><p>Before knowing about this utility, I always thought there needs to be some better way for finding optimal hyperparameters. Thanks to Dr. Adrian Rosebrock from <a href="https://www.pyimagesearch.com/">PyImagesearch</a> from whose article I came to know about this utility. The utility definitely takes a lot of time to find optimal values but think about the trial-and-errors and the manual fatigue that you get rid of. Until you are some sort of expert who can figure out the optimal values in less than 10 trials(which would be very rare), I highly recommend using this approach to save your efforts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a8cb394d0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/hyperparameter-tuning-using-keras-tuner-72a8cb394d0f">Hyperparameter Tuning using Keras Tuner</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning, the summarized way Part-2]]></title>
            <link>https://medium.com/analytics-vidhya/deep-learning-the-summarized-way-part-2-35d88351a18a?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d88351a18a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning-basics]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Wed, 12 May 2021 08:19:52 GMT</pubDate>
            <atom:updated>2021-05-12T17:00:28.257Z</atom:updated>
            <content:encoded><![CDATA[<p>In continuation to <a href="https://dhruv-pandey93.medium.com/deep-learning-the-summarized-way-part-1-23e2eee01ddd">Part-1</a>, I bring up to you, more concepts of Deep Learning in a consolidated way. Please check the Introduction and <em>“is this article for you?”</em> in the <a href="https://dhruv-pandey93.medium.com/deep-learning-the-summarized-way-part-1-23e2eee01ddd">first part</a>.</p><h3>Learning Rate and Scheduler</h3><p>The optimization algorithm tells <em>when</em> to update the model parameters. The learning rate tells <em>how much</em> update should be done to the model parameters. The goal of the optimization algorithm is to lower the loss of the model or reach the minimum point(green mark in the first image). The learning rate decides how small or big updates would be done to the model parameters during backpropagation in order to reach the minimum value or point.</p><p>Finding it hard to understand some terms, check <a href="https://dhruv-pandey93.medium.com/deep-learning-the-summarized-way-part-1-23e2eee01ddd">Part-1</a> where they have been explained clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwNMei9_dcLwZs7ogSnItg.png" /><figcaption>Learning Rate explained. Image Source: <a href="https://www.jeremyjordan.me/nn-learning-rate/">here</a>.</figcaption></figure><blockquote>Learning rate is a hyperparameter which means that you would have to update the parameter yourself and the model will not be updating(or learning) it during the training time and its value mostly lies between 0.0 and 1.0.</blockquote><p><strong>Learning Rate Scheduler: </strong>One option is that you run your model completely, wait for outputs and then tune the learning rate yourself. The other option is to define a custom function that lets Keras handle the updating process. The second option is what is called LR Scheduler. Keras provides <em>LearningRateScheduler </em>class that allows us to define a custom function and then have it automatically applied during the training process for LR calculation. This function should take the epoch number as an argument and then compute our desire learning rate based on a function that we define.</p><h3>Standard Steps in a Deep Learning problem</h3><p>There are certain fixed steps that you would have to do in any deep learning problem. Here is a small mention of these steps.</p><ol><li>Prepare a set of <strong>global variables</strong> for each hyperparameter. The variables help you to change the values right away from the top of the notebook without actually diving and searching for them in the long code.</li><li>Load the training and validation data and apply <strong>data augmentation</strong>. Perform splitting into training data if you don’t have separate validation data.</li><li>Prepare the <strong>model architecture</strong>. Each layer has an activation function that you must define. At the beginning of the Fully Connected(FC) or Dense layer, you have to flatten your input once. The final FC or Dense layer should have output the same as the number of classes that you are predicting.</li><li><strong>Compile your model</strong>. This step involves defining the loss function and optimization algorithm.</li><li><strong>Define callback functions</strong>, that your model will call at the correct time. Traning Monitor and EpochCheckpoint are highly recommended.</li><li><strong>Train your model</strong>. This is the heart of the entire pipeline and the most time-consuming part. The GPU resource is actually needed only for this step.</li><li><strong>Plot your curves</strong>. Once the training process is finished, you have the model, plot validation, and loss curves.</li><li><strong>Assess the model: </strong>If the curves look good, do some testing on the testing dataset, then some testing on real-life images. Find out the confusion matrix for the model. Totally up to you, what do you want to do with your trained model?</li><li><strong>Tweak the hyperparameters</strong> if needed. If the model didn’t perform as per expectations, do small changes to the hyperparameters.</li></ol><p>You can check my <a href="https://www.kaggle.com/pdhruv93/fingers-count-scratch">sample notebook</a> for a reference of how each step is actually performed in code.</p><h3>Underfitting and Overfitting</h3><p>This is by far the most important topic that a deep learning practitioner needs to understand. You can make good decisions on how to improve your model if you are aware of these concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*v7JeCcNp0pl__00fUIsBgA.png" /><figcaption>Correct fit vs Underfit vs Overfit</figcaption></figure><p><strong>Underfitting:</strong> Underfitting is said to occur when our model cannot capture the underlying trend of the data. <em>Poor performance on the training data and poor generalization to test data. Model, in this case, tends to have a low accuracy score on both training and test data. </em>It is quite easy to combat, just add more data for training or add more layers/neurons to your model.</p><p><strong>Overfitting: </strong>Overfitting is said to occur when our model just grasped the input data instead of trying to learn the underlying generalization. <em>Good performance on the training data, poor generalization to other data. The best</em> way to combat overfitting is to apply regularization techniques which we will discuss in the next section.</p><p>The best way to spot underfitting and overfitting is using the accuracy and loss curves. I <strong>highly recommend</strong> checking <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">this article</a>(not from me) for an excellent explanation. This will definitely help you in making decisions about improving your model performance.</p><h3>Remedies to overfitting(Regularization Techniques)</h3><ol><li><strong>Simplify model architecture:</strong> The models tend to “grasp” the input if they are too much complex as compared to the images they are supposed to be learning. Try decreasing the layers or neurons in each layer, though there is no concrete way to determine how much to remove.</li><li><strong>Use data augmentation:</strong> Try to supply a variety of data to the model.</li><li><strong>L1 and L2 Regularization:</strong> These techniques add an extra “penalty” to our original loss functions. In DL networks that operate on images, you would mostly use L2 regularization.</li><li><strong>Batch normalization:</strong> As you see overfitting has a lot to do with the input data. If instead of changing the model architecture, we could do some changes in the input data, it would again help in preventing overfitting. We add a new Batch normalization <em>layer </em>to our model which performs the standardizing and normalizing operations on the input of a layer coming from a previous layer. BN has shown to be extremely effective at reducing the number of epochs it takes to train a neural network.<br>Batch Normalization operates over channels, so we need to specify which axis to normalize over.<br><em>axis=-1 implies channel last ordering[rows][cols][channels].<br>axis=1 implies channel first ordering[channels][rows][cols].</em></li><li><strong>Dropouts: </strong>When creating the model architecture, we add Dropout layers in between. Dropout layers randomly disconnect inputs from the preceding layer to the next layer. Dropout ensures that the neurons of the next layer are not completely dependent on the previous layer neurons(so that they are not “grasping” anything). Even if some of the neurons in previous layers are turned off, the neurons in the next layer should be able to function. A <em>dropout percentage p</em> specifies that p% of the neurons in this layer would be tuned off randomly during training.</li></ol><h3>The “ideal” curve</h3><p>All the images are taken from <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*s_idtBnNJErqzR6m5EV8pQ.png" /><figcaption>Image source <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">here</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*hVF79ux1nfU_P8RKeTx7Zg.png" /><figcaption>Image source <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">here</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*HEnWPToHJHbhzQqpw25DFg.png" /><figcaption>Image source <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">here</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*Gp7V5kxBBAEJ7GzGccv6LA.png" /><figcaption>Image source <a href="https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/learning-curve-diagnostics.nb.html">here</a></figcaption></figure><h3>Some common terms</h3><ol><li><strong>Rank1 and Rank5 accuracies: </strong>Rank1 accuracy is the percentage of prediction where the top prediction matches the ground truth label. Out of 10 classes that the model had to predict, your model predicted that the image is of a dog and the ground label of that image was also a dog. This is the standard type of accuracy that you report.<br>Rank5 accuracy on the other hand goes a little soft on the model and takes the top 5 predictions made by the model. Let&#39;s say in the same previous example, the model predicted the image of the dog as a cat but if we see the top 5 predictions made by the model, there was a dog prediction also, so this case will not be counted into Rank1 accuracy but still be counted into Rank5 accuracy.</li><li><strong>Momentum: </strong>Remember this image from the learning rate discussion. the goal is to reach the bottom of the hill or slope. The momentum adds a little “<em>strength</em>” to our learning rate so that we could reach the minimum a little earlier. The speed could have been changed by changing the learning rate. Then why do we need momentum? Because it is smart as compared to the learning rate. The momentum increases the strength of updates(tweaks) for model parameters/weights whose gradients point in the same direction and decreases the strength of updates for parameters/weights whose gradients switch directions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwNMei9_dcLwZs7ogSnItg.png" /><figcaption>Learning Rate explained. Image Source: <a href="https://www.jeremyjordan.me/nn-learning-rate/">here</a>.</figcaption></figure><p>3. <strong>Nesterov&#39;s Acceleration:</strong> Let’s say you have built up the momentum and moving towards the minimum point with a huge speed, somehow you would have to decrease the speed as you are about to reach the minimum(goal). Nesterov&#39;s acceleration acts as a corrective parameter to update Momentum and provides the model the approximate idea that the model is about to reach the goal, so change your momentum accordingly.</p><h3>Transfer learning</h3><p>A deep learning model needs a good amount of input data to get trained from scratch. The size and quality of the dataset are important parameters for a successful model. It doesn’t make any sense to train a model from scratch if you don’t have a sufficient amount of data. That&#39;s where Transfer Learning comes into the picture. In transfer learning, we use some existing trained models as a starting point for our own custom model. Using Transfer Learning you can train a new model to classify class labels outside of what it was originally trained on. (All the references and Images in this section are derived from <a href="https://www.pyimagesearch.com/">PyImagesearch</a>, it is so well explained that I don’t feel like writing my own words).</p><p>There are majorly 2 ways to perform Transfer Learning:</p><ol><li><strong>Feature Extractor: </strong>When treating the network as a feature extractor, we essentially “chop off” the network at an arbitrary point (normally prior to the fully connected layers). We then pass our custom dataset to this chopped network and obtain the features that the new chopped network generates. These features are then passed to some simple classifier like(Logistic Regression)where the actual label determination work happens.<br>The original CNN itself is not responsible for recognizing these new classes, instead, we are using the CNN as an intermediary feature extractor. The downstream machine learning classifier will take care of learning the underlying patterns of the features extracted from the CNN.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*4evTleB5CO48v2zJD5xakw.png" /><figcaption>Feature Extraction</figcaption></figure><p>This is how the head-chopping is done in code:</p><pre>model = VGG16(weights=&quot;imagenet&quot;, include_top=False)</pre><p>2. <strong>Fine Tuning: </strong>Instead of simply applying feature extraction, we are going to perform <em>network surgery</em> and modify the actual architecture so we can re-train parts of the network. Applying fine-tuning allows us to apply pre-trained networks to recognize classes that they were not originally trained on; furthermore, this method can lead to higher accuracy than feature extraction. Here are the steps for this approach:</p><p>1. Take a model or architecture(like ResNet or VGGNet) and <em>cut off</em> its final set of fully-connected(FC) layers (i.e., the “head” of the network). <br>2. Replace the head with a new set of fully-connected(FC) layers with random initializations. <br>3. <em>Freeze</em> all the layers below the head so their weights cannot be updated (i.e., the backward pass in backpropagation does not reach them).<br>4. Allow the new layers to <em>warm up</em>. This is achieved by training the network using a very small learning rate so the new set of FC layers can start to learn patterns from the previously learned CONV layers earlier in the network.</p><p>Here is how the sample code looks for these steps:</p><pre>#chop off the head<br>baseModel = VGG16(weights=&quot;imagenet&quot;, include_top=False, 62 input_tensor = Input(shape=(224, 224, 3)))<br>#create new head<br>headModel = FCHeadNet.build(baseModel, len(classNames), 256)<br>#replace chopped off head with new head<br>model = Model(inputs=baseModel.input, outputs=headModel)<br><br>#Freeze layers<br>for layer in baseModel.layers:<br>    layer.trainable = False</pre><h4>When to use Transfer Learning and which method to use?</h4><p>Dr. Adrian Rosebrock from <a href="https://www.pyimagesearch.com/">PyImagesearch </a>provides an excellent way to determine when to use the Transfer Learning vs train model from scratch. I will present this in a tabular way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*PK10F7-19jUZGD3JAM7Vog.png" /><figcaption>Which approach to use? Reference from <a href="https://www.pyimagesearch.com/">PyImagesearch</a></figcaption></figure><h3>Final words</h3><p>At this point, I feel like I have covered most of the “fundamental” DL concepts. Your journey should not be limited to these articles and concepts. DL is a vast world and needs your continuous efforts and learning. It really took me a lot of effort to compile these articles, so please share them on your network. If I get more time, I will definitely come up with some next parts of this series. Once again a big thanks to Dr. Adrian Rosebrock from <a href="https://www.pyimagesearch.com/">PyImagesearch </a>and Jason Brownlee from <a href="https://machinelearningmastery.com/">MLMastery</a>, I recommend everyone to go through their articles and coding techniques which not only will help you understand DL fundamentals but will also pave your way to Practical DL techniques.</p><p><a href="https://dhruv-pandey93.medium.com/deep-learning-the-summarized-way-part-1-23e2eee01ddd"><strong><em>Link to part 1 of this article.</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d88351a18a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deep-learning-the-summarized-way-part-2-35d88351a18a">Deep Learning, the summarized way Part-2</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning, the summarized way Part-1]]></title>
            <link>https://medium.com/analytics-vidhya/deep-learning-the-summarized-way-part-1-23e2eee01ddd?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e2eee01ddd</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[machine-learning-books]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning-basics]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Wed, 12 May 2021 08:13:27 GMT</pubDate>
            <atom:updated>2021-05-12T17:00:40.821Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a lot of resources on Deep Learning available online as well as on books. But it’s hard to find a consolidated version, so I decided to come up with some articles that would present topics in a summarized way.</p><p><strong>For whom is this article?</strong> The article would really help people who had learned<strong> </strong>the<strong> </strong>basics of Deep learning and want to <em>refresh their memory</em>. I would do my best to make it friendly for newcomers but I would not cover things in too much detail.</p><p><strong>There are so many resources out there. Why this? </strong>As already mentioned it is very hard to find a consolidated resource. Trust me, I would not bloat the articles with too much theory, <em>only the necessary information</em> that refreshes your memory.</p><p><strong>A short disclaimer: </strong>To improve the understanding of a particular topic, I might use some layman analogies that would not be applicable in the real theory of that topic but will definitely help you get a better idea of the topic. Also, most of my DL knowledge is inspired by <a href="https://www.pyimagesearch.com/">Pyimagesearch</a> and <a href="https://machinelearningmastery.com/">MLMastery</a>, so you might notice some references from their articles.</p><h3>What are Keras, Tensorflow, OpenCV?</h3><p>Tensorflow and Theano are libraries that are used for general-purpose mathematical computations. While you may have heard mostly about them in the Deep learning world, but they are used in many other applications.</p><p>Keras is a deep learning framework that sits on top of Tensorflow or Theano and helps you do deep learning stuff easily and abstractly by providing so many utility functions and API. The actual deep learning work happens in the backend systems(Tensorflow or Theano) and Keras makes your life easier by taking responsibility for all the boilerplate code.</p><p>OpenCV is not at all related to the deep learning world and in general used for computer vision and basic image operations(reading/showing/manipulating images).</p><h3>What is Deep Learning?</h3><p>Deep Learning(DL) is a subfield of machine learning which is in turn is a subfield of artificial intelligence(AI).</p><p><strong>Supervised ML</strong>: The algorithm trains on a dataset that has both the inputs and outputs(labels). This algorithm aims to find the output label for unseen data that is provided. Example: Logistic Regression, Support vector machines(SVM), Artificial Neural Networks(ANN). Deep Learning uses ANN as its core and sometimes these two are used interchangeably.</p><p><strong>Unsupervised ML: </strong>The algorithm trains on a dataset that has some inputs but no labels for the input. This algorithm aims to group similar kinds of inputs under one cluster. Examples of this are k-means clustering and PCA(Principal component analysis).</p><h3>Popular Datasets and Architecture</h3><p><strong>Popular datasets:</strong> MNIST(grayscale images for handwritten digits), CIFAR-10(ten classes such as airplane, bird, cat, truck…), ImageNet(dataset having 22,000 classes).</p><p><strong>Popular Architectures:</strong> AlexNet, VGGNet, ResNet, MobileNet, GoogLeNet.</p><p>The ‘Net’ word at the end of the name really made me confused if it was a dataset or the architecture. For example, ImageNet is a dataset whereas ResNet is an architecture.</p><h3>DL Network ingredients</h3><ol><li><strong><em>Dataset:</em></strong> Since deep learning is a type of supervised learning, your data should have input as well as output labels.</li><li><strong><em>A model/architecture:</em></strong><em> </em>Number of layers, number of neurons in each layer.</li><li><strong><em>Loss Function:</em></strong> Quantifies how “good” or “bad” the model is performing when learning on the training dataset. If classes are &gt;2, we use <em>categorical cross-entropy</em>. For 2 classes we use<em> binary cross-entropy</em>.</li><li><strong><em>Optimization methods</em></strong>: Based on the value that we obtain from the above step(how good or bad the model was), what should be the approach that should be used to tweak the model parameters. Some techniques are Stochastic Gradient Descent(SGD), RMSProp, Adagrad, Adadelta, Adam.</li></ol><h3>Model parameters vs Hyperparameters</h3><p>A model parameter is a variable whose value the “<em>model can learn</em>” by itself during training time. The model parameters in DL Network are usually assigned some initial values(<em>the library handles this on its own, nothing expected from you</em>) and the model learns the best values of these parameters during training time. The best example of this type of parameter would be the <em>weights</em> of neurons/nodes in a neural network.</p><p>A hyperparameter is a variable whose value is <em>expected from you</em> and the value of this parameter is <em>never estimated or learned by the model</em> based on the dataset. There is definitely an option to update the value at training time(using concepts like decay) but that needs to be done by you and the model is not doing this. Some examples are the <em>learning rate</em>, number of epochs. These are the parameters that work on trial and error, you would have to tweak them continuously to improve your model but as you gain experience, you become good at defining them.</p><blockquote>Model weights are model parameters whereas Learning Rate, Batch Size and Number of epochs are hyperparameters.</blockquote><h3>Dataset</h3><p><strong>Training dataset: </strong>The data that is used by the model to fit its model parameters. This dataset participates during model training.</p><p><strong>Validation dataset: </strong>The data that is <em>used by the model</em> to report the accuracy or loss after each epoch at training time. This dataset also participates during model training.</p><blockquote>If you see the below sample output, the model does one epoch of training using the training dataset, then uses validation dataset to check how well it did in the current epoch and based on it tweaks its model parameters.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*pf7tPdEMNlSFCZp7k4yMig.png" /><figcaption>Sample output of the model training</figcaption></figure><p><strong>Testing dataset: </strong>Data which is <em>used by you</em> to assess how the model is performing after it has been trained. This dataset is solely for your testing and the model never uses it during training time.</p><blockquote>So validation dataset is used by model for assesmment purpose whereas testing dataset is used by you for assessment purpose.</blockquote><blockquote>Usually, the validation dataset can be derived from the training dataset(20% of the training dataset) but if the training dataset is very small, you can use testing dataset as the validation dataset.</blockquote><h3>Epochs vs Batch</h3><p>At the time of training, the model picks a sample from the training dataset, tries to predict the output using its current model parameters, and based on how good or bad this prediction was, it tries to tweak its model parameters.</p><p>The <strong>batch size</strong> represents the number of samples that the model processes before it tweaks the model parameters. It can tweak it after every 1 sample(batch size=1) or maybe after the entire dataset(batch size=length of the dataset).</p><p>The number of <strong>epochs </strong>is the number of complete passes/rounds through the training dataset. Let’s say you have 5 epochs. So if the model has reached the end of your dataset, it will jump back to the first sample of the dataset, again traverse and process the entire dataset till the end and this cycle would be repeated 5 times.</p><p>If you see below the sample output of the training process, you notice we have 20 epochs and 18000 steps per epoch. Steps per epoch is normally calculated using length _of _your_datset//BATCH_SIZE, you still have the option to provide your custom value but I recommend using this formula).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*mmep9bY0fe48dt7DrtNeEQ.png" /><figcaption>Sample output from the training process</figcaption></figure><p>Note that the batch size is different from steps per epoch. The steps per epoch is actually calculated based on batch size, but the tweaking of parameters happens as per the value of batch size and not of steps per epoch.</p><h3>Some common terms</h3><ol><li><strong>Backpropagation: </strong>The working principle of any Deep Learning model primarily involves 2 processes:<br>The model picks a batch of images from the input dataset and tries to predict each image&#39;s output using its current model parameters. This is Forward propagation.<br>Based on how good or bad the prediction was, the model calculates the gradient(error) and uses this gradient to update all the model parameters. This is called Backpropagation.</li><li><strong>One Hot encoding:</strong> Let’s say you have a dataset, where the output labels are some constant values for example, “cat” or “dog” or “0” “1”. The Deep Learning model cannot work on these kinds of labels, instead, it expects them to be some kind of vectors. One hot encoding converts these labels to some kind of vectors. For example “cat” would be converted to [0, 0, 1], “dog” would be converted to [0, 1, 0].</li><li><strong>Viewing model architecture as an image:</strong> The <em>plot_model()</em> function of Keras helps you plot and visualize your model. It gives all the details about the layers, inputs, and outputs.</li><li><strong>Saving model to disk: </strong>The <em>model.save()</em> lets you serialize the model to disk in HDF5 format.</li></ol><h3>Optimization Methods Explained</h3><p>After the forward pass is completed, the model needs to update its parameters. What strategy the model uses for this update is decided by the Optimization algorithm that we use while defining the model architecture. Here are some commonly used Optimization algorithms:</p><ol><li><strong>Vanilla Gradient Descent(VGD): </strong>The vanilla here just represents that this is the traditional Gradient Descent algorithm where the model updates its parameters(specifically weights)<strong> </strong>after traversing the entire dataset.</li><li><strong>Stochastic Gradient Descent(SGD):</strong> Here the model updates its parameters after processing small batches of training data.</li></ol><blockquote><strong>VGD:</strong> batch_size=length of dataset; <strong>SGD: </strong>1&lt;batch_size&lt;=some random number less than the length of dataset.</blockquote><p>3. <strong>Adagrad: </strong>Larger updates are performed on parameters that change infrequently while smaller updates are done on parameters that change frequently. The primary advantage is that we don&#39;t have to manually tune the learning rate, the adaptive nature of the algorithm helps to tune automatically. The disadvantage is that there are some cache issues that were later fixed with <strong>Adadelta</strong>.</p><p>4. <strong>RMSProp</strong></p><p>5. <strong>Adam</strong></p><p><strong>Which one’s to use?</strong></p><blockquote>I have hardly seen people using any optimization methods other than SGD and Adam. Dr. Adrian Rosebrock from PyImagesearch personally recommends starting with SGD, then Adam, and finally RMSProp, as Adam tends to outperform RMSProp in most situations.</blockquote><h3>Data Augmentation</h3><p>Your model is as good as the dataset it is working upon. So your dataset should cover all possible scenarios that the model might see in the real world. Data augmentation picks an image from the dataset and applies various transformations(like rotation, zoom, shear) to the image which would then be fed to the deep learning model. The sole purpose is to train our model with all the possibilities of varying data.</p><p>We use <em>ImageDataGenerator </em>to handle data augmentation for us. This is how the code looks</p><pre>traindatagen = ImageDataGenerator(zoom_range=0.15, fill_mode=&quot;nearest&quot;, rescale=1. / 255, width_shift_range=0.1,<br>                                  height_shift_range=0.1)<br><br>train_generator = traindatagen.flow_from_directory(directory=&quot;./train_custom&quot;, target_size=(128, 128),<br>                                                   batch_size=BATCH_SIZE, class_mode=&quot;categorical&quot;)</pre><p>The <em>flow_from_directory()</em> method is very handy for loading the dataset. The only pre-requirement for this is that it expects the data to be kept in the hierarchical folder structure(I usually prepare this kind of folder structure using custom python scripts if it is not already there). The alternate option is <em>flow()</em> which doesn’t expect this folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*ePtWUibTQv1FlNaqyaHuxg.png" /><figcaption><em>flow_from_directory() needs this type of </em>hierarchical folder structure. Folder1, Folder2 represents each class</figcaption></figure><blockquote>Data Augmentation is only applied to training and validation datasets and never applied to the testing datasets.</blockquote><h3>Handy Callbacks(Training Monitor and Model Checkpoint)</h3><p><strong>Training Monitor: </strong>As already mentioned the model hyper-parameters is something that you would have to tweak yourself seeing the current model performance. You cannot just predict model hyperparameters and expect them to work the first time. But what if your model takes 23hours to complete training. Will you wait for 23hours and then make the decisions about tweaking. You cannot just sit and wait for training to complete and then check the training performance. Instead, the model performance monitoring should be done parallelly along with the training. That&#39;s where the Training monitor comes in handy.</p><blockquote>Keras allows you to define your custom callback functions and pass them to the model. These functions would be called by the Keras whenever the model is getting trained. You also have the option to specify when(after epoch completed or before training started or after training completed) Keras should be calling your functions during model training. Keras also pass the model parameters that your function requests like current training accuracy, validation loss, etc. You can even provide multiple callback functions and they would be called by Keras in order.</blockquote><p>Based on the parameters that your callback function received from Keras during model training, you can make decisions like plotting a graph for accuracy or loss and saving them to disk. This helps you visualize and assess your model training parallelly as the model is getting trained.</p><p>I will not be discussing how you can create this type of Training monitor but you can check a sample(not my code) <a href="https://github.com/agoila/lisa-faster-R-CNN/blob/master/pyimagesearch/callbacks/trainingmonitor.py">here</a>.</p><p><strong>Model Checkpoint: </strong>What happens if your training process was about to complete but somehow your system turned off or the cloud session went away. There should be some automated way that stores/checkpoints your model on the disk when your model meets a certain condition(let’s say after every 10epochs or when the model performance increases). Once you have the model on your disk you can resume the training from the same point where it was stooped. The same callback principle is used here also and you can specify when your checkpointing should happen. Keras will call your checkpointing function during the training time. Here is a small example of how I define my checkpoint callback:</p><pre>filepath = &quot;./checkpoints/model-checkpoint-{epoch:02d}-{val_accuracy:.2f}.hdf5&quot;<br>modelCheckPoint = ModelCheckpoint(filepath, monitor=&#39;val_accuracy&#39;, verbose=1, save_best_only=True, mode=&#39;max&#39;)</pre><p>I want Keras to checkpoint my model every time the validation accuracy of my model increases. Once you have defined all your callback functions, this is how you pass these callbacks to the model:</p><pre>H = model.fit(train_generator, steps_per_epoch=len(train_generator) // BATCH_SIZE,<br>              validation_data=test_generator, validation_steps=len(test_generator) // BATCH_SIZE, epochs=EPOCHS,<br>              <strong>callbacks=[TrainingMonitor(&quot;./perEpochGraph.png&quot;), modelCheckpoint]</strong>)</pre><h3>Final Words</h3><p>I hope you like this article and it really refreshed your Deep Learning knowledge. It really takes a lot of effort to compile something like this, so please share the article on your network and don’t forget to check <a href="https://dhruv-pandey93.medium.com/deep-learning-the-summarized-way-part-2-35d88351a18a"><strong>the next part</strong></a> which covers some more concepts. Again a big thanks to Dr. Adrian Rosebrock from <a href="https://www.pyimagesearch.com/">PyImagesearch </a>and Jason Brownlee from <a href="https://machinelearningmastery.com/">MLMastery</a>, who not only helped me understand DL fundamentals but also paved my way to Practical DL techniques.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e2eee01ddd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deep-learning-the-summarized-way-part-1-23e2eee01ddd">Deep Learning, the summarized way Part-1</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GUI based approach for Deep Learning using Edge Impulse]]></title>
            <link>https://medium.com/analytics-vidhya/gui-based-approach-for-deep-learning-using-edge-impulse-2c6565d09d25?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6565d09d25</guid>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[edge-impulse]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 16:50:49 GMT</pubDate>
            <atom:updated>2021-04-30T15:48:48.294Z</atom:updated>
            <content:encoded><![CDATA[<p>In a practical deep learning approach, you write code for everything. You preprocess your data using code, create and train the model using code, create output visualizations through code, everything through code. What if I say you could minimize your coding efforts using a tool that requires only drag and drop and does the behind stuff all by itself. Sounds interesting.</p><h3>Available GUI-based options in the market</h3><p>There aren’t many such tools that provide GUI based approach for deep learning. Big platforms like Azure have these kinds of utilities in their Machine Learning module but they come with a big cost. Even the cloud platforms like Google Colab and Kaggle are very good in terms of resources(datasets, GPU) they provide, but lacks this GUI-based approach. Recently I came across the <a href="https://www.edgeimpulse.com/"><strong>Edge Impulse</strong></a> platform that has got almost everything you would need while working on your Deep learning world.</p><h3>Is the GUI-based approach suitable for me?</h3><p>The idea behind writing this article is not to discourage you from writing your own code and rely completely on this tool. There are people who always prefer the command line and there are people who might feel it as confusing and prefer using a graphical interface. As per my recommendation you should be aware of both the ways and use either of them as per your feasibility and requirements. I created some kind of meter that helps you decide about the usability of this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNB1q8W9V3FPsELfe-K6Pg.png" /><figcaption>Is the GUI approach right for you?</figcaption></figure><h3>Edge Impulse and its features</h3><p>The main motivation behind <a href="https://www.edgeimpulse.com/">this platform</a> was to make machine learning possible on the <a href="https://searchnetworking.techtarget.com/definition/edge-device">edge devices</a>(like Raspberry Pi or Arduino or Jetson Nano). A device like Raspberry Pi or Arduino lacks enough resources(like GPU) that are needed in abundance when training a deep learning model. The idea was to perform the heavy load work(model training) on the Edge Impulse platform and return the trained model back to the edge device so all that the edge device has to do is use the model and perform detections or classifications. Even though the platform is meant for edge devices, you can still use it with your normal system. Some features that I really liked about this platform was:</p><ol><li>Connect multiple devices to the platform. You can also treat your mobile phone as a device:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*hx1em_8bW9blQCa-hRURBA.png" /><figcaption>Multiple Device Options</figcaption></figure><p>2. There are so many ways and sources to prepare your input data. You can connect your device directly to this platform and take pictures using the device’s camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*dcSM2VAuVdBocA_Zo2txqA.png" /><figcaption>Multiple ways to prepare input data</figcaption></figure><p>3. Last but not least, it has a drag and drop UI and everything is so user-friendly for code management, testing, and deployment.</p><h3>Let’s train a model on Edge Impulse</h3><p>I would be using the <a href="https://www.kaggle.com/pdhruv93/mask-vs-no-mask/#data">following dataset</a> for demonstration purposes. The goal of this model would be to detect if the person in the image is wearing a face mask or not. <em>This dataset is completely owned by Kaggle and I don’t have any ownership of this dataset. </em>I have also created my model using the traditional Jupyter notebook approach, you can check it <a href="https://www.kaggle.com/pdhruv93/mask-vs-no-mask/">here</a>. In the rest of this article, we will focus on how to use this dataset for model creation without writing any piece of code.</p><ol><li><strong>Upload Dataset files: </strong>The first step that you perform is uploading the dataset into the platform. As already mentioned you can upload directly from your system or take pictures from the device’s camera. This image would be quite self-explanatory and I have highlighted major steps. Once you have uploaded the dataset, you will have your data dashboard, don’t forget to check it as it super awesome!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QnbSvR0uOWw6MLt7zaSdg.png" /><figcaption><strong>Step 1</strong>: Dataset Preparation</figcaption></figure><p>2. <strong>Create Impulse(pipeline): </strong>This is the heart of the whole process. You decide the steps and create a pipeline for your model training. You can perform data resizing, data preprocessing, add multiple preprocessing blocks. <em>Each step in the pipeline has its name</em> and the yellow lines in the image show how each step is connected to the next step in the pipeline. I have added short explanations on the image itself but it would be more clear when you visit the tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75KEZyFMCEgZG9HCSk3Gvg.png" /><figcaption><strong>Step 2:</strong> Creating an Impulse(Pipeline)</figcaption></figure><p>3. <strong>Defining your parameters: </strong>Once you save the impulse, the tool asks you to define your parameters for training purposes. If you notice on the left-hand side, you will now see a separate link for each block that you created in the previous step. You have to visit each block and tune the parameters as per your requirement. Some of the blocks may not need any input from you and for some, it is mandatory to add parameters from your side. Each block link will also show the output of that step on the same tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*q4FrCZvuN-1ZZvjm88JgHg.png" /><figcaption><strong>Step 3:</strong> Define your parameters</figcaption></figure><p>4. <strong>Start Training: </strong>Once you have decided the parameters, you just have to click “Start Training” and the tool will start executing the pipeline that you have defined. All the live logs and errors will be shown on the right-hand side. After the training is completed, the tool will show the final results like this(there is a lot that the tool will show, I am just putting a small image):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*NFYpVFKihl85cg4PThjUrA.png" /><figcaption><strong>Step 4:</strong> Results</figcaption></figure><p>5.<strong> Use the trained model:</strong> Once the impulse(model) is trained, the tool gives you the option to retrain the model, test the model, live classification or deploy the model to your connected devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*WDlouWbjjHpoFb_uu7yX8Q.png" /><figcaption><strong>Step 5:</strong> Use the trained model</figcaption></figure><h3>Don’t forget to check these awesome features</h3><p>I am not sure about others, but I was very fascinated by the UI features that this platform provides. I know most of this can be prepared by writing code, but how easy was it to do everything without writing a single line of code. I will put some features list that I really liked and you should definitely check them in case you missed them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vk5nSITMvoHswidyrG8WEA.png" /><figcaption>Data dashboard for your uploaded data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYy_MdRPFbJKUMevMendYw.png" /><figcaption>Live Data Testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf8MqoN4tS9dR-9d6HAnDw.png" /><figcaption>Live classification using the trained model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*u5P_9kVrpAdeZKhPnu49PA.png" /><figcaption>Easy deployment to any of your edge device</figcaption></figure><h3>Final Words</h3><p>I would again like to mention that the idea behind writing this article is not to discourage you from writing your own code and rely completely on GUI. You should be aware of what the tool might be doing behind the scenes even if you are using drag and drop functionality. And yes at some point we have to accept that the GUI-based approach is more user-friendly and less time-consuming as compared to writing code. Deep learning is still evolving and you can expect more such tools coming up in the market, some of them might become industry standards, so go and get a taste of them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6565d09d25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/gui-based-approach-for-deep-learning-using-edge-impulse-2c6565d09d25">GUI based approach for Deep Learning using Edge Impulse</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eye Aspect Ratio(EAR) and Drowsiness detector using dlib]]></title>
            <link>https://medium.com/analytics-vidhya/eye-aspect-ratio-ear-and-drowsiness-detector-using-dlib-a0b2c292d706?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b2c292d706</guid>
            <category><![CDATA[dlib]]></category>
            <category><![CDATA[facial-landmarks]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[eye-aspect-ratio]]></category>
            <category><![CDATA[facedetection]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Wed, 21 Apr 2021 13:55:51 GMT</pubDate>
            <atom:updated>2021-04-21T16:12:35.350Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will show you how to determine facial landmarks using the <em>dlib </em>library, how to calculate EAR(Eye Aspect Ratio), and use the concept of EAR to detect drowsiness.</p><blockquote>Before you begin with the code part of this article, you would have to install dlib library in python. There are some prerequisites for installing dlib library and I would recommend you to check <a href="https://medium.com/analytics-vidhya/how-to-install-dlib-library-for-python-in-windows-10-57348ba1117f">this article</a>.</blockquote><h3>What are facial landmarks that dlib detects</h3><p>The <em>dlib</em> library can be used to detect a face in an image and then find 68 facial landmarks on the detected face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*WPh1v9qIrn5D7RU-fWqS5A.png" /><figcaption>68 facial landmarks that dlib finds in a face</figcaption></figure><p>I will not go into details about how does it detect a face and locate facial landmarks. The order of the detected facial landmarks will always be the same irrespective of image dimensions or face size, which means 1–17 will always represent an outline of the face. 43–48 would always represent the left eye. The exact code of how this is done comes later in this article.</p><h3>How to find Eye Aspect Ratio(EAR)</h3><p>If you notice, each eye is represented using 6 landmarks points.</p><p>The EAR for a single eye is calculated using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*b42_JrQKCi0sTh9dV1s0Og.png" /><figcaption>||p2-p6|| means the distance between points p2 and p6</figcaption></figure><blockquote>The more the EAR, the more widely eye is open. We would decide a minmum EAR value and used this to decide if the eye is closed or not.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*8bQB2IjpraO9gegFGkZmiw.png" /></figure><p>Here is the utility function that would return the EAR for a single eye</p><pre>def eye_aspect_ratio(eye):<br>    p2_minus_p6 = dist.euclidean(eye[1], eye[5])<br>    p3_minus_p5 = dist.euclidean(eye[2], eye[4])<br>    p1_minus_p4 = dist.euclidean(eye[0], eye[3])<br>    ear = (p2_minus_p6 + p3_minus_p5) / (2.0 * p1_minus_p4)<br>    return ear</pre><h3>The Main code(Drowsiness Detector)</h3><ol><li>We will start by importing the necessary python libraries</li></ol><pre>import cv2<br>import dlib<br>import imutils<br>from imutils import face_utils<br>from scipy.spatial import distance as dist</pre><p>2. We then declare some global configuration variables, that would be used in the rest of our code:</p><pre>FACIAL_LANDMARK_PREDICTOR = &quot;shape_predictor_68_face_landmarks.dat&quot;  <br>MINIMUM_EAR = 0.2<br>MAXIMUM_FRAME_COUNT = 10</pre><p><em>FACIAL_LANDMARK_PREDICTOR: </em>path to dlib’s pre-trained facial landmark predictor. You can download this file from <a href="https://github.com/davisking/dlib-models/blob/master/shape_predictor_68_face_landmarks.dat.bz2">here</a>.</p><p><em>MINIMUM_EAR:</em> Minimum EAR value above which the eyes would be marked as open otherwise closed. This parameter you might want to tune as per your requirement. Try to find EAR in different scenarios and then determine the value. Also, note that this EAR is not for a single eye but the cumulated EAR for both eyes.</p><p><em>MAXIMUM_FRAME_COUNT: </em>The value of EAR changes very quickly. Even if you blink your eye the EAR will drop quickly. But blinking does not mean drowsiness. Drowsiness would be a situation where a person has closed his eye(his EAR is very less) for let’s say 10 consecutive video frames. So this variable tells the maximum number of consecutive frames in which EAR can remain less than <em>MINIMUM_EAR</em>, otherwise alert drowsiness.</p><p>3. We then instantiate dlib’s <em>faceDetector</em>(that will detect the face in an image) and <em>landmarkFinder</em>(which will find 68 landmarks in the detected face)</p><pre>faceDetector = dlib.get_frontal_face_detector(<br>landmarkFinder = dlib.shape_predictor(FACIAL_LANDMARK_PREDICTOR)<br>webcamFeed = cv2.VideoCapture(0)</pre><p>4. We then find the start and end values of landmark ids for both the eye. You can do it manually also(37–42 for the right eye and 43–48 for the left eye) but using <em>face_utils </em>you can get these values by just passing the eye name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*9o6QqU6964HqfNjKuOQCJQ.png" /><figcaption>dlib facial landmarks</figcaption></figure><pre>(leftEyeStart, leftEyeEnd) = face_utils.FACIAL_LANDMARKS_IDXS[&quot;left_eye&quot;]<br>(rightEyeStart, rightEyeEnd) = face_utils.FACIAL_LANDMARKS_IDXS[&quot;right_eye&quot;]</pre><p>5. The final part is where the real stuff happens</p><pre>EYE_CLOSED_COUNTER = 0<br>try:<br>    while True:<br>        (status, image) = webcamFeed.read()<br>        image = imutils.resize(image, width=800)<br>        grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br><br>        faces = faceDetector(grayImage, 0)<br><br>        for face in faces:<br>            faceLandmarks = landmarkFinder(grayImage, face)<br>            faceLandmarks = face_utils.shape_to_np(faceLandmarks)<br><br>            leftEye = faceLandmarks[leftEyeStart:leftEyeEnd]<br>            rightEye = faceLandmarks[rightEyeStart:rightEyeEnd]<br><br>            leftEAR = eye_aspect_ratio(leftEye)<br>            rightEAR = eye_aspect_ratio(rightEye)<br><br>            ear = (leftEAR + rightEAR) / 2.0<br><br>            leftEyeHull = cv2.convexHull(leftEye)<br>            rightEyeHull = cv2.convexHull(rightEye)<br><br>            cv2.drawContours(image, [leftEyeHull], -1, (255, 0, 0), 2)<br>            cv2.drawContours(image, [rightEyeHull], -1, (255, 0, 0), 2)<br><br>            if ear &lt; MINIMUM_EAR:<br>                EYE_CLOSED_COUNTER += 1<br>            else:<br>                EYE_CLOSED_COUNTER = 0<br><br>            cv2.putText(image, &quot;EAR: {}&quot;.format(round(ear, 1)), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)<br><br>            if EYE_CLOSED_COUNTER &gt;= MAXIMUM_FRAME_COUNT:<br>                cv2.putText(image, &quot;Drowsiness&quot;, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)<br><br>        cv2.imshow(&quot;Frame&quot;, image)<br>        cv2.waitKey(1)<br>except:<br>    pass</pre><p>We declare a variable <em>EYE_CLOSED_COUNTER</em> which records the count of consecutive frames in which the EAR was less than the <em>MINIMUM_EAR.</em></p><p>We do some resizing to the image and convert it to grayscale.</p><p>Detect all the faces in the image using dlib’s <em>faceDetector</em>:</p><pre>faces = faceDetector(grayImage, 0)</pre><p>Loop over each face and find the 68 landmarks using the <em>landmarkFinder</em> of dlib:</p><pre>faceLandmarks = landmarkFinder(grayImage, face)</pre><p>Get the landmarks for the left and right eye and then send them to <em>eye_aspect_ratio()</em> to get EAR values for the left and right eye:</p><pre>leftEye = faceLandmarks[leftEyeStart:leftEyeEnd]<br>rightEye = faceLandmarks[rightEyeStart:rightEyeEnd]<br><br>leftEAR = eye_aspect_ratio(leftEye)<br>rightEAR = eye_aspect_ratio(rightEye)</pre><p>Find the cumulative EAR for both eyes:</p><pre>ear = (leftEAR + rightEAR) / 2.0</pre><p>Use the eye landmarks to show eyes on the image:</p><pre>cv2.drawContours(image, [leftEyeHull], -1, (255, 0, 0), 2)<br>cv2.drawContours(image, [rightEyeHull], -1, (255, 0, 0), 2)</pre><p>If for the current frame the cumulative EAR is less than the MINIMUM_EAR, increase the counter else reset the counter as we are interested in consecutive frames only.</p><pre>if ear &lt; MINIMUM_EAR:<br>     EYE_CLOSED_COUNTER += 1<br>else:<br>     EYE_CLOSED_COUNTER = 0</pre><p>If the EAR was less than the MINIMUM_EAR for the specified number of consecutive frames, this implies drowsiness.</p><pre>if EYE_CLOSED_COUNTER &gt;= MAXIMUM_FRAME_COUNT:<br>                cv2.putText(image, &quot;Drowsiness&quot;, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)</pre><p>Once everything is in place, and you run the code, it will generate an output something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*3tugfKaP5fOKE5f0Q7PFvQ.png" /><figcaption>EAR(without rounding off to 1 decimal place) is less than MINMIUM_EAR(0.2), drowsiness reported</figcaption></figure><h3>Final words</h3><p>In this article, we used dlib library for determining facial landmarks. The dlib library is pretty simple to use and works smoothly even without GPU. But there might also be other free-to-use libraries available on the market. Mediapipe is one such example. If you are not aware of this library you can check my <a href="https://medium.com/analytics-vidhya/mediapipe-hand-gesture-based-volume-controller-in-python-w-o-gpu-67db1f30c6ed">previous article</a> covering this library. At the time of writing this article, the Face module of the Mediapipe library is not available for Python. At some later time, if the Face module becomes available, it is definitely worth giving it a try as for sure the facial landmarks detection of Mediapipe would be better than the dlib. You can find the source code for this article on Github <a href="https://github.com/pdhruv93/computer-vision/tree/main/drowsiness-detector">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b2c292d706" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/eye-aspect-ratio-ear-and-drowsiness-detector-using-dlib-a0b2c292d706">Eye Aspect Ratio(EAR) and Drowsiness detector using dlib</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lane detection for a self-driving car using OpenCV]]></title>
            <link>https://medium.com/analytics-vidhya/lane-detection-for-a-self-driving-car-using-opencv-e2aa95105b89?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2aa95105b89</guid>
            <category><![CDATA[self-driving-cars]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[hough-transform]]></category>
            <category><![CDATA[lane-detection]]></category>
            <category><![CDATA[line-drawing]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 11:50:36 GMT</pubDate>
            <atom:updated>2021-04-21T16:12:39.736Z</atom:updated>
            <content:encoded><![CDATA[<p>To all the people who are wondering how can this concept be covered inside an article, I would say things sound complicated until you have explored the depths of it. I will not say that the article would be very easy but yes it would be built on top of pretty basic computer vision concepts. Please do not presume that this is exactly what Tesla would be using in their cars, but it might be something similar.</p><p><strong>What are the prerequisites?</strong> Some basic knowledge of OpenCV would be good. If not, don’t worry I will try to explain the OpenCV functions that I will use and also put references for you to check them in more detail.</p><p>Each section of this article would cover a function that would finally be used in the main part of the program. Also, in this article, I will demonstrate everything using an image. You can reuse the same code to use on a video(since the video is just a collection of images).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3BuOdElSbg4nIb09P_CTA.png" /><figcaption>The image that I will use for this article</figcaption></figure><h3>Step 1: Edge Detection</h3><p>We would be using Canny edge detection. If you are not sure what is this, check out my <a href="https://medium.com/analytics-vidhya/image-simplification-through-binarization-in-opencv-1292d91cae12">previous article</a> that explains it in a practical way.</p><pre>def canyEdgeDetector(image):<br>    edged = cv2.Canny(image, 50, 150)<br>    return edged</pre><p>This is how the output looks after we applied canny edge detection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YGV_7Ov8a9JeolJnUA0rA.png" /><figcaption>Output after Canny edge detection</figcaption></figure><h3>Step 2: Define ROI(Region of Interest)</h3><p>While driving, to keep a car on the lane you focus only on the next 100meteres of your current road. Also, you don’t care about the road on another side of the divider. This is what is our <em>region of interest</em>. We hide the unnecessary details from the image and show only the region which would help us in finding the lane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uffjcrzYap__4dd7M6oVAg.png" /><figcaption>The Red triangle shows our Region of Interest</figcaption></figure><pre>def getROI(image):<br>    height = image.shape[0]<br>    width = image.shape[1]<br>    # Defining Triangular ROI: The values will change as per your camera mounts<br>    triangle = np.array([[(100, height), (width, height), (width-500, int(height/1.9))]])<br>    # creating black image same as that of input image<br>    black_image = np.zeros_like(image)<br>    # Put the Triangular shape on top of our Black image to create a mask<br>    mask = cv2.fillPoly(black_image, triangle, 255)<br>    # applying mask on original image<br>    masked_image = cv2.bitwise_and(image, mask)<br>    return masked_image</pre><ol><li>We have defined the triangular ROI, whose coordinates will change depending on where you have mounted the camera on your car(try to have only that part of the image which will actually contribute towards lane detection).</li><li>We have created a black image of the same shape as that of our original image:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*1E4GQp1tOdfqfoifDnyQtw.png" /><figcaption>Creating a black image of the same shape as the original image</figcaption></figure><p>3. <strong>Create a Mask:</strong> We then use <em>cv2.fillPoly()</em> to put our triangle shape(with white-colored lines)on top of our black image to create a mask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*bDFHGLoRrswBkRrvAIfSIQ.png" /><figcaption>Create a mask</figcaption></figure><p>4. Apply the mask on our original image to get cropped image having only our ROI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eejLU4rD-LU7RGdhXwZy7Q.png" /><figcaption>Original Image + Mask = Final Image with ROI</figcaption></figure><p>The output of this step would be something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXxjhojr01VdNRpxoy61Xw.png" /><figcaption>Output after getROI()</figcaption></figure><blockquote>It is important to apply edge detection before getting ROI otherwise edge detection will detect boundaries of our ROI too.</blockquote><h3>Step 3: Get Lines</h3><p>The next step would be to pass the ROI to get all the straight lines in the image. The <em>cv2.HoughLinesP()</em> helps you achieve this. This function returns a list of all the straight lines that it can find in the input image. Each line is represented by [x1, y1, x2, y2].</p><p>Now, this may look very simple but the underlying working principle of Hough Lines detection is a little bit time taking to explain. So I would not cover it in this article. Instead, I suggest you have a look at <a href="https://www.youtube.com/watch?v=7m-RVJ6ABsY">this tutorial</a> (#28, #29, #30 should be sufficient to understand Hough Lines Principle).</p><pre>def getLines(image):<br>    lines = cv2.HoughLinesP(image, 0.3, np.pi/180, 100, np.array([]), minLineLength=70, maxLineGap=20)<br>    return lines</pre><p>The parameters of the cv2.HoughLinesP() must be tuned as per your requirement(try to change and debug what works out best for you). But I think the ones above should work in most of the cases. This is how the output of this step looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zelUwhKEkek6LONCMigPRw.png" /><figcaption>3 Lines detected in the image. There can be hundreds of lines that may be detected in your image. So tune your parameters to obtain as fewer lines as you can get</figcaption></figure><h3>Step 4: Some utility functions</h3><p>The following utility function takes an image and list of lines and draws the lines on the image. (This step is not taking any input from Step3. Instead, this is just a utility step that would be called from Step5, so you make first have a look at Step5 and visit this step when needed).</p><pre>def displayLines(image, lines):<br>    if lines is not None:<br>        for line in lines:<br>            x1, y1, x2, y2 = line.reshape(4) #converting to 1d array<br>            cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 10)<br>    return image</pre><p>We define another utility function to get line coordinates from its parameters(slope and intercept). Keep in mind that a line is represented by <em>y=mx+c </em>where m is the slope and c is the intercept.</p><pre>def getLineCoordinatesFromParameters(image, line_parameters):<br>    slope = line_parameters[0]<br>    intercept = line_parameters[1]<br>    y1 = image.shape[0]  # since line will always start from bottom of image<br>    y2 = int(y1 * (3.4 / 5))  # some random point at 3/5<br>    x1 = int((y1 - intercept) / slope)<br>    x2 = int((y2 - intercept) / slope)<br>    return np.array([x1, y1, x2, y2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*TlowOsXP_8K2TLDFe3AFcg.png" /><figcaption>Notice how did we select values for y1 and y2</figcaption></figure><h3><strong>Step 5: Getting Smooth line</strong></h3><p>Once we have obtained lines from Step 3, in this step we are dividing those lines into 2 groups(left and right). If you notice the output image from Step3, this step will put Line1 and Line 2 into the <em>left group</em> and Line3 into the <em>right group</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*FaBe4GOSyIyoLc48XZ55_Q.png" /><figcaption>How to get a common line for the left and right side of the lane</figcaption></figure><p>Once grouped, we find the average slope(m) and intercept(c) for that group and try to create a line for each group by calling getLineCoordinatesFromParameters() and passing average m and average c.</p><p>Here is the function that does all of this:</p><pre>def getSmoothLines(image, lines):<br>    left_fit = []  # will hold m,c parameters for left side lines<br>    right_fit = []  # will hold m,c parameters for right side lines<br><br>    for line in lines:<br>        x1, y1, x2, y2 = line.reshape(4)<br>        parameters = np.polyfit((x1, x2), (y1, y2), 1)<br>        slope = parameters[0]<br>        intercept = parameters[1]<br><br>        if slope &lt; 0:<br>            left_fit.append((slope, intercept))<br>        else:<br>            right_fit.append((slope, intercept))<br><br>    left_fit_average = np.average(left_fit, axis=0)<br>    right_fit_average = np.average(right_fit, axis=0)<br><br>    # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters<br>    left_line = getLineCoordinatesFromParameters(image, left_fit_average)<br>    right_line = getLineCoordinatesFromParameters(image, right_fit_average)<br>    return np.array([left_line, right_line])</pre><p>This is how the image looks after the lines have been grouped:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT72TaYU7cuEI7o5Nn8ujQ.png" /><figcaption>Output after lines grouping</figcaption></figure><h3>The Main Code(calling above steps one by one)</h3><p>Once we have the individual functions ready, we just have to call them in our main code and you would have lanes detected in your image.</p><pre>image = cv2.imread(&quot;3.jpg&quot;) #Load Image<br><br>edged_image = canyEdgeDetector(image)   # Step 1<br>roi_image = getROI(edged_image)         # Step 2<br><br>lines = getLines(roi_image)             # Step 3<br><br>smooth_lines = getSmoothLines(image, lines)    # Step 5<br>image_with_smooth_lines = displayLines(image, smooth_lines) # Step 4<br><br>cv2.imshow(&quot;Output&quot;, image_with_smooth_lines)<br>cv2.waitKey(0)</pre><p>The output will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56_Mzzdq-wNkaPsIp0IUjg.png" /><figcaption>The final output with the determined lane</figcaption></figure><h3>Final Words</h3><p>You made it to the end of the article. Once things are sorted and works fine for the image, you know how to get it working on a video. You may have realized how you can use the very basic computer vision operations cleverly in order to achieve something this useful. Again I will say do not try to compare this work with what bigger companies like Tesla have done(the base for them is also something similar). Use this as motivation instead and maybe at some point, you are able to achieve something similar.</p><p>Till then keep exploring :) You can check the link to the Github source code for this article <a href="https://github.com/pdhruv93/computer-vision/tree/main/lane-detection-self-driving">here</a>.</p><p><em>Sample output after detecting lanes on a video(the frames are slow because of the video recorder):</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJH-wQc4pSbI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJH-wQc4pSbI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJH-wQc4pSbI%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/46e078eaf5a35e35c3561f60e1cabb02/href">https://medium.com/media/46e078eaf5a35e35c3561f60e1cabb02/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2aa95105b89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/lane-detection-for-a-self-driving-car-using-opencv-e2aa95105b89">Lane detection for a self-driving car using OpenCV</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contours and Convex Hull in OpenCV Python]]></title>
            <link>https://medium.com/analytics-vidhya/contours-and-convex-hull-in-opencv-python-d7503f6651bc?source=rss-ff2a7e9bdeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7503f6651bc</guid>
            <category><![CDATA[convexity-defect]]></category>
            <category><![CDATA[convex-hull]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[contour]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Dhruv Pandey]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 07:40:53 GMT</pubDate>
            <atom:updated>2021-04-19T17:14:39.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Answers to most computer vision problems lie in finding and analyzing the shapes present in the image, and getting the contour is one such approach for it. To a beginner, I would explain a contour as “<em>simply as a curve joining all the points lying on the boundary of that shape</em>”.</p><p>Let&#39;s say I have the following image of my hand, the contour of the hand would be the curve represented by the green line. The red dots show the points by connecting which we are making up the contour curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*S6qd7TxmhYCyImzgmIof9A.png" /><figcaption>Contour points(Red). Connecting contour points, we create the contour curve(Green)</figcaption></figure><p>Following would be contours for the common shapes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*aq7hzQc3oard4WjlzxXkcw.png" /><figcaption>Contour(Green) for the common shapes</figcaption></figure><p>I still remember my advanced mathematics class where they taught contours. But it was hard to connect with the importance of this topic since the teacher never mentioned any applications of the contour in the actual world. And today is the day when I realize how important they are in computer vision.</p><h3>Finding Contours in OpenCV</h3><blockquote>The only pre-condition that you need to find contours in an image is that the image should be binary. To know in detail about binary images, check my <a href="https://dhruv-pandey93.medium.com/image-simplification-through-binarization-in-opencv-1292d91cae12">article</a>.</blockquote><p>So I converted my image to binary using Canny edge detection discussed in the previous article:</p><pre>binary_image = edgeDetection(image)<br>contours, hierarchy = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)</pre><p>Once you have the binary image, you just need to pass it to <em>findContours()</em> and that’s it you have the contours ready for you. Before we proceed let’s discuss the other arguments to this function.</p><p><strong><em>2nd argument(Contour retrieval mode):</em></strong> <br>A shape(or a contour) may be present inside another shape(or contour). So we may call the outer shape the parent and inner shape as a child. The retrieval mode argument decides if want the output of the contours list in a hierarchical(parent-child) manner or we simply want them as a list(having no hierarchy). Use <em>cv2.RETR_LIST</em> for no hierarchy/plain list. Check more variants <a href="https://docs.opencv.org/4.5.1/d9/d8b/tutorial_py_contours_hierarchy.html">here</a>.</p><p><em>Note:</em> <em>there is no impact on contour detection. Just the response representation gets changed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*HzUjeHJoJ5wnD3s3btNJmA.png" /><figcaption>Contour Hierarchy</figcaption></figure><p><strong><em>3rd argument(Contour approximation):</em> </strong><br>A contour is simply a shape represented by a collection of points(red dots in the very first image). So this argument specifies how many points should be stored so that the contour shape is preserved and can be redrawn. <em>cv2.CHAIN_APPROX_NONE</em> signifies that we store all the points(no approximation). It takes more storage space but if there is a zig-zag line, we definitely need to store all the points to preserve the contour shape. But in the case of a straight line, 2 points would be enough as the points in between can be approximated based on the equation of a straight line, so we use <em>cv2.CHAIN_APPROX_SIMPLE.</em></p><p>The output <em>contours </em>is a list of contour points each having an x and y coordinate.</p><h3>Operations on Contours</h3><ol><li><strong>Contour Area:</strong> You can sort the contours based on their area.</li></ol><pre>contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)</pre><p>2. <strong>Contour perimeter: </strong>You can calculate the perimeter for each contour.</p><pre>for contour in contours:<br>    perimeter = cv2.arcLength(contour, True)</pre><p>3. <strong>Vertices of a contour: </strong>Since we know that the contour is just the representation of x and y coordinates of its points. So getting the length of the contour, gives us the vertices of the contour.</p><pre>len(contour) == 4   #Rectangle</pre><p>4. <strong>Contour Approximation: </strong>This is a little bit tricky, so needs more explanation. This is very similar to 3rd argument that we discussed above, just it gives us more manual control.</p><p>Let’s say OpenCV detected a contour as shown in the below image(1). What do you think would be the closest regular shape that can be obtained, definitely a line(assuming that the peak is not important to us). Also since the peak is not important to us, why waste our storage to store coordinates of the peak. Instead if somehow we can approximate this contour to a line, we only need 2 coordinates to store our contour. This is what the <em>cv2.approxPolyDP() </em>does for us. It tries to approximate the irregular contour to some other shape so that the contour can be simplified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkEkMkI7roXHWmS65EwbaQ.png" /><figcaption>How contour approximation is controlled</figcaption></figure><p>How do we control this approximation? The <em>cv2.approxPolyDP() </em>takes an <em>epsilon</em> parameter whose value tells OpenCV, how much deviation we can allow from the original shape in order to receive our simplified contour. Image(3) shows an epsilon of 10% which means we are somewhat willing to get the simplified contour(a straight line as in 5). Image(4) shows an epsilon of 20% which means we are more willing to get the simplified contour(a straight line as in 5). See the peak moves down towards a straight line as we increase the epsilon value. <em>More epsilon means more willingness to get simplified contour.</em></p><pre>for contour in contours:<br>    perimeter = cv2.arcLength(contour, True)<br>    approximatedShape = cv2.approxPolyDP(contour, 0.02 * perimeter, True)</pre><p>See how we passed the second parameter(epsilon). The last parameter just says if want a closed contour.</p><p>5. <strong>Minimum Enclosing Circle: </strong>Using minEnclosingCircle() you can find a circle that completely covers the contour of the object with a minimum area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*Vbw3X6dekkNiZub2CD61Cg.png" /></figure><pre>(centerXCoordinate, centerYCoordinate), radius = cv2.minEnclosingCircle(contour)</pre><p>6. <strong>Moments: </strong>The moments let you extract important contour’s physical properties like the center of mass of the object, area of the object, etc.</p><pre>for contour in contours:<br>    moment = cv2.moments(contour)</pre><p>You can use the moment to calculate further important attribute of contour like centroid:</p><pre>centroidXCoordinate = int(moment[&#39;m10&#39;] / moment[&#39;m00&#39;])<br>centroidYCoordinate = int(moment[&#39;m01&#39;] / moment[&#39;m00&#39;])</pre><p>You can check more such operations permitted on a contour <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html">here</a>.</p><h3>Convex Hull</h3><p>If explained in layman terms, a convex hull of an object is the <em>minimum </em>boundary that can completely enclose or wrap the object(or contour of that object).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*yOK58dmzVVTgAGCmyJWs2Q.png" /><figcaption>Reference is taken from <a href="https://theailearner.com/2019/12/05/finding-convex-hull-opencv-python/">here</a></figcaption></figure><p>There are many algorithms that can be used to find the convex hull for a given contour but I would not be discussing them in detail in this article. Once you find out the contours, it is pretty straightforward to find the convex hull</p><pre>for contour in contours:<br>    convexHull = cv2.convexHull(contour)<br>    cv2.drawContours(image, [convexHull], -1, (255, 0, 0), 2)<br><br># Display the final convex hull image<br>cv2.imshow(&#39;ConvexHull&#39;, image)<br>cv2.waitKey(0)</pre><h3>Convexity Defects</h3><p>Any deviation of the contour from its convex hull is known as the convexity defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-oQr4F4lYcMRO4l4oCgXjg.png" /><figcaption>The vertical lines in the last image are what we call the convexity defects</figcaption></figure><p><em>Note: There can be multiple convexity defect points where the hull deviates from the contour but in the last image I have only shown major convexity defects so as not to confuse.</em></p><p>OpenCV provides a simple way to find the convexity defects from contour and hull:</p><pre>convexityDefects = cv2.convexityDefects(contour, convexhull)</pre><p><em>convexityDefects </em>contains a list of all the convexity defects found. Each element in this list has the following attributes:</p><p><em>[start point, endpoint, farthest point, approximate distance to farthest point]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*Q9UVsouEISLEdMlWAU7zGw.png" /><figcaption>Values for a particular convexity defect(3,4)</figcaption></figure><h3>Final Words</h3><p>Most computer vision problems will have their solution lying in</p><ol><li>Finding the contours, and</li><li>Applying the contour operations to obtain desired results.</li></ol><p>From my personal experience, I would say that point 1 is not a difficult thing but point 2 would require most of your efforts and careful inspection and debugging of the results at the end of each step before you move on to the next.</p><p>Hope his article gives you a good onboarding to Contours. I would be writing more articles about some real-life projects where we are actually applying contours. So don’t forget to check them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7503f6651bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/contours-and-convex-hull-in-opencv-python-d7503f6651bc">Contours and Convex Hull in OpenCV Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>