<?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 Aby Varghese on Medium]]></title>
        <description><![CDATA[Stories by Aby Varghese on Medium]]></description>
        <link>https://medium.com/@abypaulvarghese?source=rss-70147804920a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CqfkJc3X4AinWcMZ.jpg</url>
            <title>Stories by Aby Varghese on Medium</title>
            <link>https://medium.com/@abypaulvarghese?source=rss-70147804920a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:55:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abypaulvarghese/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[How I Built an AI-Powered CCTV Footage Analyzer for Law Enforcement to detect evidences quickly]]></title>
            <link>https://medium.com/@abypaulvarghese/how-i-built-an-ai-powered-cctv-footage-analyzer-for-law-enforcement-to-detect-evidences-quickly-9686242574ba?source=rss-70147804920a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9686242574ba</guid>
            <category><![CDATA[law-enforcement]]></category>
            <category><![CDATA[cctv-footage-analysis]]></category>
            <category><![CDATA[crime-analytics-software]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[video-analysis]]></category>
            <dc:creator><![CDATA[Aby Varghese]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 06:16:17 GMT</pubDate>
            <atom:updated>2026-04-30T07:04:21.664Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into ObjectScope — a GPU-accelerated object detection system designed to help police and security agencies rapidly identify criminal activity across thousands of hours of surveillance video.</em></p><h3>The Problem: Drowning in CCTV Footage</h3><p>Every day, law enforcement agencies around the world face the same overwhelming challenge: <strong>too much video, too little time.</strong></p><p>A single crime scene investigation can generate hundreds of gigabytes of footage from nearby CCTV cameras. Reviewing it manually — officer by officer, hour by hour — is slow, expensive, and error-prone. Crucial evidence gets missed. Suspects escape identification. Investigations stall.</p><p>The question isn’t whether AI can help. It’s <em>how to build a system that’s actually fast enough, reliable enough, and practical enough</em> to be used in the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OWzxopXUxVcedaT-" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve A Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>ObjectScope</strong> is my answer to that question.</p><p>It’s a Python-based application that converts large CCTV video files into frames using FFmpeg, then runs GPU-accelerated YOLOv8 object detection across all of those frames — streaming results to investigators in real time, sorted by confidence, with annotated bounding boxes. What used to take a team of analysts days can now be triaged in minutes.</p><h3>The Workflow: From Raw CCTV Video to Actionable Intelligence</h3><p>The pipeline has two stages:</p><h3>Stage 1: Video → Frames (FFmpeg)</h3><p>Raw CCTV footage — often in formats like .mp4, .avi, .mkv, or .h264 — is first converted into individual image frames using FFmpeg. This is done as a preprocessing step before ObjectScope runs.</p><p>bash</p><pre># Extract 1 frame per second from a video<br>ffmpeg -i cctv_footage.mp4 -vf fps=1 ./frames/frame_%05d.jpg</pre><pre># Extract every frame (full fidelity)<br>ffmpeg -i cctv_footage.mp4 ./frames/frame_%05d.jpg</pre><pre># Extract frames from a specific time window (e.g., 14:00–15:00)<br>ffmpeg -i cctv_footage.mp4 -ss 00:14:00 -to 00:15:00 -vf fps=2 ./frames/frame_%05d.jpg</pre><p>For a 2-hour CCTV recording at 25fps, extracting 1 frame per second yields <strong>7,200 frames</strong>. At 2fps it’s <strong>14,400</strong>. ObjectScope is designed to handle this volume efficiently.</p><blockquote><strong><em>Tip for investigators:</em></strong><em> For initial triage, 1fps is usually sufficient to detect people, vehicles, and objects. For detailed event reconstruction, use 5–10fps around windows of interest.</em></blockquote><h3>Stage 2: Frame Analysis (ObjectScope)</h3><p>Once frames are extracted to a folder, ObjectScope takes over — scanning every image with YOLOv8, caching results, and streaming detections back to the investigator’s browser in real time.</p><h3>What ObjectScope Detects</h3><p>ObjectScope is trained on the <strong>COCO dataset’s 80 object classes</strong>, organized into investigation-relevant categories:</p><p>CategoryDetectable Objects🚶 People &amp; Suspectsperson (with confidence scoring)🚗 Vehiclescar, motorcycle, truck, bus, bicycle, boat🎒 Items of Interestbackpack, handbag, suitcase, umbrella⚽ Potential Weapons / Objectsbaseball bat, knife, scissors🏙️ Scene Contexttraffic light, stop sign, fire hydrant, bench📱 Electronicscell phone, laptop, TV🐾 Animalsdog, cat, horse, bird</p><p>An investigator looking for a suspect carrying a backpack near a specific vehicle type can <strong>filter to exactly those classes</strong> and get only the relevant frames — ranked by detection confidence.</p><h3>Architecture: Built for Scale and Speed</h3><h3>The Core Challenge</h3><p>Processing 10,000+ frames from a single investigation’s worth of CCTV footage requires more than just calling a detection model in a loop. Naive single-image inference would take hours. The architecture of ObjectScope is designed around one goal: <strong>maximize GPU throughput while keeping the investigator’s interface responsive in real time.</strong></p><h3>1. GPU Batch Inference — The Speed Multiplier</h3><p>The single most impactful performance decision is <strong>batched GPU inference</strong>. Instead of processing frames one at a time, ObjectScope groups them into batches and sends them to the GPU in a single model.predict() call:</p><p>python</p><pre>raw_results = model.predict(<br>    source=paths,   # a list of N frame paths<br>    verbose=False,<br>    device=device,<br>    imgsz=640,<br>)</pre><p>Batch size is configurable based on available GPU memory:</p><pre>4 GB VRAM  →  BATCH_SIZE=8<br>8 GB VRAM  →  BATCH_SIZE=16<br>16 GB VRAM →  BATCH_SIZE=32<br>24 GB+ VRAM → BATCH_SIZE=64</pre><p>On a mid-range GPU (RTX 3080), this yields approximately <strong>50–100 frames per second</strong> — meaning 10,000 frames from a full investigation can be processed in under 3 minutes.</p><p>If a batch fails due to memory pressure, the system automatically falls back to single-image inference so no frame is silently skipped:</p><p>python</p><pre>except Exception as e:<br>    log_batch.error(f&quot;Batch FAILED → falling back to single-image inference&quot;)<br>    for p in paths:<br>        r = model.predict(source=p, verbose=False, device=device, imgsz=640)<br>        raw_results.extend(r)</pre><h3>2. Prefetch Queue — Keeping the GPU Fed</h3><p>GPU starvation happens when the processor finishes a batch and then has to wait for disk I/O to load the next one. ObjectScope eliminates this with a <strong>producer/consumer prefetch queue</strong>:</p><p>python</p><pre>prefetch_q: queue.Queue = queue.Queue(maxsize=BATCH_SIZE * 4)</pre><p>A background Prefetch thread reads the next batch of image paths from disk while the GPU is still processing the current one. The GPU is never idle waiting for I/O — critical when processing thousands of high-resolution CCTV frames from slow storage.</p><h3>3. Content-Addressable Detection Cache</h3><p>In a real investigation, footage is reviewed multiple times. An investigator might run one pass looking for vehicles, then another for people, then re-examine specific time windows. <strong>Re-running GPU inference on already-processed frames wastes time and compute.</strong></p><p>ObjectScope uses a persistent <strong>content-addressable cache</strong> keyed by a fast hash of each file’s path, size, and modification timestamp:</p><p>python</p><pre>def file_hash(path: str) -&gt; str:<br>    s = os.stat(path)<br>    return hashlib.md5(f&quot;{path}:{s.st_size}:{s.st_mtime}&quot;.encode()).hexdigest()</pre><p>On every detection run, frames are split into two groups:</p><ul><li><strong>Cache hits</strong> → detection results served instantly, zero GPU cost</li><li><strong>Cache misses</strong> → sent to the GPU pipeline and stored for future runs</li></ul><p>The cache is persisted to disk as detection_cache.json. This means:</p><ul><li><strong>First run</strong> on a new set of footage: full GPU processing</li><li><strong>Every subsequent run</strong> on the same footage (different categories, different filters): nearly instant</li></ul><p>For an investigation with 50,000 frames reviewed multiple times by multiple officers, this is the difference between a minutes-long process and an hours-long one.</p><h3>4. Three-Phase Detection Pipeline</h3><p>Every analysis run follows a structured pipeline:</p><p><strong>Phase 1 — Folder Scan &amp; Cache Split</strong> Walk the frames folder, hash every image, and categorize into cache hits vs. new frames requiring GPU. A 10,000-frame folder scan completes in under 1 second.</p><p><strong>Phase 2 — Serve Cache Hits</strong> Immediately stream results for previously-seen frames to the investigator’s browser. Results appear within seconds of starting a run — before the GPU has even begun on new footage.</p><p><strong>Phase 3 — GPU Batch Inference</strong> Process new frames in configurable batches. Each batch’s results are stored in the cache and broadcast to all connected browser clients as they complete, sorted by confidence score.</p><p>This design means the investigator sees value <strong>immediately</strong> and results keep appearing as the GPU works through the backlog.</p><h3>5. Real-Time Streaming with Server-Sent Events (SSE)</h3><p>ObjectScope doesn’t make investigators wait for a full analysis to complete before showing results. It uses <strong>Server-Sent Events (SSE)</strong> to push detections to the browser the moment each batch finishes:</p><p>python</p><pre>def _broadcast(event: str, data: dict):<br>    msg = f&quot;event: {event}\ndata: {json.dumps(data)}\n\n&quot;<br>    for q in _sse_clients:<br>        q.put_nowait(msg)</pre><p>Multiple officers can connect simultaneously — each gets a live stream of results as detection progresses. Events include:</p><ul><li>status — live progress (frames processed, cache hits, GPU name, current batch)</li><li>new_result — a single frame detection ready to display immediately</li><li>live_update — new matches found by the live watcher</li><li>done — analysis complete with final match count</li></ul><h3>6. Live Folder Watcher — Real-Time Ingestion</h3><p>One of ObjectScope’s most operationally valuable features is its <strong>live folder watcher</strong>. After completing an initial analysis run, it continues monitoring the frames folder for newly added files:</p><p>python</p><pre>WATCH_INTERVAL = float(os.environ.get(&quot;WATCH_INTERVAL&quot;, &quot;3&quot;))  # seconds</pre><p>Every 3 seconds (configurable), the watcher checks for new frames. When it finds them, it immediately runs GPU batch inference and broadcasts results.</p><p><strong>Why this matters for law enforcement:</strong> While one analyst reviews results, a colleague can be extracting more footage with FFmpeg into the same folder. ObjectScope processes new frames automatically — no need to restart the analysis. This creates a <strong>continuous ingestion pipeline</strong>: extract footage → frames appear in folder → ObjectScope detects → results stream to investigator, all concurrently.</p><h3>7. Annotated Frame Export</h3><p>Every frame containing a detection can be exported with <strong>visual bounding boxes</strong> drawn directly onto the image — suitable for evidence documentation, briefings, or court submissions.</p><p>The annotation engine uses Pillow to draw color-coded boxes with class labels and confidence percentages:</p><p>python</p><pre>label_text = f&quot;{det[&#39;label&#39;]} {det[&#39;conf&#39;]:.0%}&quot;<br>draw.rectangle([x1, y1, x2, y2], outline=color, width=lw)<br>draw.text((x1 + 4, label_y + 3), label_text, fill=(255, 255, 255), font=font)</pre><p>Each COCO class has a consistent, reproducible color (seeded deterministically), so the same object type always appears in the same color across all frames. Exported packages include a manifest.json with metadata — timestamps, categories searched, total detections — for chain-of-custody documentation.</p><h3>8. Confidence-Sorted Results</h3><p>Results are maintained in a <strong>sorted list ordered by detection confidence</strong>, using binary search insertion:</p><p>python</p><pre>def _insert_sorted(result: dict):<br>    lo, hi = 0, len(_results)<br>    while lo &lt; hi:<br>        mid = (lo + hi) // 2<br>        if _results[mid][&quot;best_conf&quot;] &gt;= result[&quot;best_conf&quot;]:<br>            lo = mid + 1<br>        else:<br>            hi = mid<br>    _results.insert(lo, result)</pre><p>This means the highest-confidence detections — the frames where the model is <em>most certain</em> a target object is present — always appear first. For investigators triaging hundreds of results, this is critical: the most actionable frames surface immediately, even before the full run is complete.</p><h3>9. Structured, Color-Coded Logging</h3><p>ObjectScope uses a custom logging formatter with ANSI color codes — making it easy for operators to visually distinguish log levels in the terminal during a live investigation run:</p><pre>DEBUG    → cyan    (cache hits/misses, batch detail)<br>INFO     → green   (run progress, GPU stats)<br>WARNING  → yellow  (fallbacks, missing files)<br>ERROR    → red     (batch failures, I/O errors)<br>CRITICAL → magenta (system-level failures)</pre><p>Separate loggers handle different subsystems — batch inference, folder watching, cache operations, and API requests — making it straightforward to audit exactly what the system did during a given run.</p><h3>Deployment Guide</h3><h3>Prerequisites</h3><p>bash</p><pre>pip install flask flask-cors ultralytics torch pillow numpy<br># FFmpeg must be installed separately for the video extraction step</pre><h3>Running the Server</h3><p>bash</p><pre># Basic<br>python app.py</pre><pre># Production configuration<br>IMAGE_FOLDER=./investigation_frames \<br>BATCH_SIZE=32 \<br>WATCH_INTERVAL=3 \<br>python app.py</pre><p>The server starts on <a href="http://0.0.0.0:5001.">http://0.0.0.0:5001.</a></p><h3>Full Investigation Workflow</h3><p>bash</p><pre># Step 1: Extract frames from CCTV footage (FFmpeg)<br>mkdir ./frames<br>ffmpeg -i cctv_camera_01.mp4 -vf fps=1 ./frames/cam01_frame_%05d.jpg<br>ffmpeg -i cctv_camera_02.mp4 -vf fps=1 ./frames/cam02_frame_%05d.jpg</pre><pre># Step 2: Start ObjectScope<br>IMAGE_FOLDER=./frames python app.py</pre><pre># Step 3: Trigger detection via API<br>curl -X POST <a href="http://localhost:5001/api/detect/start">http://localhost:5001/api/detect/start</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;folder&quot;: &quot;./frames&quot;, &quot;categories&quot;: [&quot;person&quot;, &quot;car&quot;, &quot;motorcycle&quot;, &quot;backpack&quot;]}&#39;</pre><pre># Step 4: Open browser → <a href="http://localhost:5001/">http://localhost:5001</a><br># Results stream live, sorted by confidence</pre><pre># Step 5: Export annotated frames for evidence documentation<br>curl -X POST <a href="http://localhost:5001/api/export">http://localhost:5001/api/export</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;dest_folder&quot;: &quot;./evidence_export&quot;, &quot;annotated&quot;: true, &quot;limit&quot;: 500}&#39;</pre><h3>Performance Benchmarks</h3><p>ScenarioPerformanceFrame extraction (FFmpeg, 1fps, 2hr video)~7,200 frames in ~60sFirst-run GPU inference (RTX 3080, batch=16)50–100 frames/secRe-analysis of cached footage&lt; 1 second per 10,000 framesFolder scan (10,000 frames)&lt; 1 secondCPU fallback (no GPU)~2–5 frames/second</p><h3>Key Engineering Lessons</h3><p><strong>1. Batch everything.</strong> The GPU is a massively parallel processor. Single-image inference uses a fraction of its capability. Batching is the single biggest performance lever — the difference between analyzing footage in minutes versus hours.</p><p><strong>2. Cache aggressively.</strong> Investigations revisit the same footage repeatedly. A persistent content-addressable cache makes every subsequent pass nearly free.</p><p><strong>3. Stream results, don’t wait.</strong> An investigator shouldn’t stare at a progress bar before seeing anything. SSE streaming means the highest-confidence results appear within seconds, continuously.</p><p><strong>4. Prefetch I/O concurrently with GPU compute.</strong> A producer/consumer queue keeps the GPU saturated even with slow storage — critical for large investigation datasets.</p><p><strong>5. Prioritize by confidence.</strong> In a triage context, the investigator’s time is the scarcest resource. Highest-confidence detections first means the most actionable evidence surfaces immediately.</p><p><strong>6. Degrade gracefully.</strong> Batch GPU failures fall back to single-image inference. No CUDA means CPU mode. The system always completes — it adjusts speed to available hardware.</p><h3>What’s Next</h3><ul><li><strong>YOLOv8m/l/x models</strong> — trade speed for accuracy for high-stakes analysis</li><li><strong>Custom fine-tuned models</strong> — train on domain-specific objects such as weapons, license plates, or specific clothing</li><li><strong>Timestamp reconstruction</strong> — map frame filenames back to exact video timestamps for precise event timelines</li><li><strong>Multi-camera correlation</strong> — cross-reference detections across concurrent camera feeds from the same scene</li><li><strong>Face detection pipeline</strong> — integrate a separate face detection model for suspect identification workflows</li><li><strong>Database backend</strong> — replace the JSON cache with PostgreSQL for multi-investigator, multi-case deployments</li><li><strong>Docker packaging</strong> — one-command deployment for field deployment on agency hardware</li><li><strong>Redaction mode</strong> — blur non-relevant individuals for privacy-compliant evidence sharing</li></ul><h3>Conclusion</h3><p>The gap between the volume of CCTV footage generated every day and the capacity of law enforcement to review it manually is enormous — and growing. ObjectScope is a practical, deployable step toward closing that gap.</p><p>By combining FFmpeg’s frame extraction with YOLOv8’s detection accuracy, GPU batch inference, persistent caching, and real-time result streaming, it’s possible to build a system that lets a single investigator triage <strong>hours of footage in minutes</strong> — surfacing the frames that matter, ranked by confidence, with visual annotations ready for evidence documentation.</p><p>The full source code is available on GitHub. If you’re working on public safety technology, computer vision for security applications, or large-scale video analysis pipelines, I’d love to hear how you’re applying it.</p><p><strong>Disclaimer:</strong> <em>ObjectScope is a technical tool designed to assist human investigators — not replace human judgment. All detections should be reviewed and verified by qualified personnel before being used in any investigative or legal context.</em></p><p>Tags: computer-vision law-enforcement cctv-analysis yolov8 object-detection python flask pytorch surveillance-technology public-safety ffmpeg gpu-computing real-time-ai criminal-justice-technology</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9686242574ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cultivating a Greener Future: Our Sustainable Farming and Water Conservation Journey at Home using…]]></title>
            <link>https://medium.com/@abypaulvarghese/cultivating-a-greener-future-our-sustainable-farming-and-water-conservation-journey-at-home-using-c9386a33a80c?source=rss-70147804920a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9386a33a80c</guid>
            <category><![CDATA[sustainable-farming]]></category>
            <category><![CDATA[smart-farming]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[drip-irrigation]]></category>
            <dc:creator><![CDATA[Aby Varghese]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 14:57:31 GMT</pubDate>
            <atom:updated>2024-02-11T14:57:31.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cultivating a Greener Future: Our Sustainable Farming and Water Conservation Journey at Home using ESP32 and Blynk App.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tlANBemijNYegi0Q" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Introduction<br> <br><br>In the realm of sustainable home farming, a cutting-edge approach harnesses the power of IoT technology, featuring a four-channel relay board and the ESP32 micro controller. This setup seamlessly connects to the Blynk server, transforming an ordinary home garden into a smart, automated oasis.</p><p><strong>The Core Solution- ESP32-based Smart, Remote-Controlled Automated Irrigation System</strong></p><p>The core of this setup revolves around a water outlet equipped with a filtering mechanism designed to eliminate any impurities from the water source.</p><p>Connected to this filter is a twelve-volt solenoid valve, serving as the gatekeeper for water flow. The valve opens and closes with the application of a twelve-volt signal, orchestrated by a microcontroller, specifically the ESP32. This microcontroller is integrated into a relay board, acting as the intermediary between the ESP32 and the solenoid valve. When triggered, the relay initiates the valve’s action, enabling or halting water flow to a drip irrigation system.</p><p>What sets this project apart is its connectivity. The ESP32, perched on the relay board, establishes a connection to the home WiFi network. This connectivity extends further through the integration with the Blynk platform. The ESP32 relay board communicates with the Blynk server via home WiFi, allowing users to remotely control the water system through a dedicated app on their mobile devices.</p><p><strong>High level Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a873mNvNnsY-47CmrlpepA.jpeg" /></figure><p>This smart water management system offers users unparalleled convenience. With the Blynk app, users can monitor and control the water flow from anywhere with internet access.</p><p>At the core of this innovation is the ESP32 microcontroller, orchestrating a precise watering schedule every three hours. The ESP32 is programmed to water the plants for 3 minutes every 3 hours. I have programmed it in such a way that it does not water the plants at night. So, the system won’t water the plants from night 10 PM to morning 6 AM. This optimizes resource utilization and ensures plants’ well-being through an interconnected relay system that activates a water valve for a brief three-minute interval.</p><p>Transform your home into an efficient, manless farm with ESP32 technology. You can monitor CPU temperature and available memory remotely from your mobile device, ensuring seamless operation and allowing prompt identification of defects.</p><p>What sets this system apart is its global accessibility. Integrated with Blynk, users can remotely monitor and control their home farm from anywhere in the world, offering convenience without compromising on sustainability. An uninterrupted power supply and reliable internet connectivity guarantee the system’s continuous operation.</p><p>The synergy between technology and sustainability is exemplified in the personalized user experience facilitated by the Blynk app. With real-time updates, watering schedules, and completion notifications accessible on a mobile device, this smart farming solution embodies a harmonious blend of innovation and eco-consciousness, making sustainable and man-less home farming a reality for enthusiasts worldwide.</p><p><strong>Source code</strong></p><p>You can find the source code of the ESP32 app from here.</p><p><a href="https://github.com/abypaulvarghese56/SmartFarm/blob/master/Blynk_TimeTrigger.ino">SmartFarm/Blynk_TimeTrigger.ino at master · abypaulvarghese56/SmartFarm</a></p><p>Code explanation</p><p>The below code is responsible for setting up the blynk configuration. You need to go to Blynk and then create a template ID and an authentication token.</p><pre>#define BLYNK_TEMPLATE_ID           &quot;&lt;insert Blynk Template&gt;&quot;<br>#define BLYNK_TEMPLATE_NAME         &quot;Quickstart Template&quot;<br>#define BLYNK_AUTH_TOKEN            &quot;&lt;insert BLYNK AUTH Token from BLYNK&gt;&quot;<br><br>/* Comment this out to disable prints and save space */<br>#define BLYNK_PRINT Serial<br><br></pre><p>The below section is to measure the temperature of the ESP32 chip that is built into the hardware.</p><pre>#include &lt;WiFi.h&gt;<br>#include &lt;WiFiClient.h&gt;<br>#include &lt;BlynkSimpleEsp32.h&gt;<br>#include &lt;esp_task_wdt.h&gt;<br><br><br>#define BLYNK_FIRMWARE_VERSION        &quot;0.1.1&quot;<br><br>//Watchdog Timer Delay- 5 minutes.<br>#define WDT_TIMEOUT 300<br><br>#ifdef __cplusplus<br>  extern &quot;C&quot; {<br> #endif<br><br>  uint8_t temprature_sens_read();<br><br>#ifdef __cplusplus<br>}<br>#endif</pre><p>The below section is defining how long the system should sleep . In this case it is sleeping for 3 hours. The IP configuration is set to use static IP to avoid problems during IP address re negotiation which might happen when DHCP is trying to renew the IP.</p><pre><br>uint64_t uS_TO_S_FACTOR =1000000ull;<br>uint64_t TIME_TO_SLEEP = 3600*3;<br><br>uint64_t SLEEP_INTERVAL = TIME_TO_SLEEP * uS_TO_S_FACTOR; <br>uint64_t SLEEP_TIMER_INTERVAL = TIME_TO_SLEEP * 1000;<br>uint8_t temprature_sens_read();<br><br>IPAddress local_IP(192, 168, 1, 8);<br>IPAddress gateway(192, 168, 1, 1);<br>IPAddress subnet(255, 255, 0, 0);<br>IPAddress dns(192, 168, 1, 1);<br><br>// Your WiFi credentials.<br>// Set password to &quot;&quot; for open networks.<br><br>char ssid[] = &quot;&lt;Your_wifi_ssid&gt;&quot;;<br>char pass[] = &quot;&lt;Your wifi password&gt;&quot;;<br>int LED_BUILTIN = 2;<br>int RELAY_PIN = 23 ;<br>int FAN_PIN = 22;<br>int BUZZER_PIN = 34;<br><br>int internetConnectedState  =0;<br>int PreviousMinimumFreeMemory = 0;<br><br>const char* ntpServer = &quot;pool.ntp.org&quot;;<br>const long  gmtOffset_sec = 19800;<br>const int   daylightOffset_sec = 0;<br><br>//V2- CPU Temp<br>//V4- Last System updated Time<br>//V5 - Last Relay activatted Time<br>//V7-  Last Relay De activated Time<br>//V6 - System Operation Status<br>//V8- Free Memory since boot<br>//V9 - Get Wifi Signal strength<br><br></pre><p>Here is the rest of the code. This handles the below key functionalities sequentially</p><ol><li>Setup- Initiates the PINS as input and output.</li><li>WatchDog timer to check if the ESP32 hung in any case. If so it restarts . The standard functions esp_task_wdt_init(WDT_TIMEOUT, true); &amp; esp_task_wdt_add(NULL) are used</li><li>configTime — Get the time from NTP Server</li><li>connectToWifi()- Connect to the local wifi</li><li>myTimerEvent()- This is the key function that triggers the relay in every 3 hours. It will then update the blynk server with the values.</li></ol><pre>BlynkTimer timer;<br>BlynkTimer timerFAN;<br><br><br>// This function is called every time the Virtual Pin 0 state changes<br>BLYNK_WRITE(V0)<br>{<br>  // Set incoming value from pin V0 to a variable<br>  int value = param.asInt();<br><br>  // Update state<br>  Blynk.virtualWrite(V1, value);<br>  //digitalWrite(LED_BUILTIN, value);<br>}<br><br>// This function is called every time the device is connected to the Blynk.Cloud<br>BLYNK_CONNECTED()<br>{<br>  // Change Web Link Button message to &quot;Congratulations!&quot;<br>  Blynk.setProperty(V3, &quot;offImageUrl&quot;, &quot;https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations.png&quot;);<br>  Blynk.setProperty(V3, &quot;onImageUrl&quot;,  &quot;https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations_pressed.png&quot;);<br>  Blynk.setProperty(V3, &quot;url&quot;, &quot;https://docs.blynk.io/en/getting-started/what-do-i-need-to-blynk/how-quickstart-device-was-made&quot;);<br>}<br><br><br>void printLocalTime()<br>{<br>  time_t rawtime;<br>  struct tm timeinfo;<br>  if(!getLocalTime(&amp;timeinfo))<br>  {<br>    Serial.println(&quot;Failed to obtain time&quot;);<br>   return;<br>  }<br>  char timeStringBuff[50]; //50 chars should be enough<br>  strftime(timeStringBuff, sizeof(timeStringBuff), &quot;%A, %B %d %Y %H:%M:%S&quot;, &amp;timeinfo);<br>  //print like &quot;const char*&quot;<br>  Serial.println(timeStringBuff);<br><br>  //Optional: Construct String object <br>  String LastUpdatedtime(timeStringBuff);<br>  if (connectToBlynk() )<br>  Blynk.virtualWrite(V4 , LastUpdatedtime); <br>  Blynk.run();<br>}<br>void myTimerEventForFAN()<br>{<br>      <br>      Serial.println(&quot;Fan event&quot;);<br><br>}<br>void UpdateWifiSignal()<br>{<br>  <br>  if (connectToBlynk() )<br>  {<br>    Blynk.virtualWrite(V9 , WiFi.RSSI()); <br>    Blynk.run();<br>  }<br>  <br>}<br>// This function sends Arduino&#39;s uptime every second to Virtual Pin 2.<br>void myTimerEvent()<br>{<br>  // You can send any value at any time.<br>  // Please don&#39;t send more that 10 values per second.<br>  //Blynk.virtualWrite(V2, millis() / 1000);<br> // Blynk.virtualWrite(V4, 1);<br>  if( (WiFi.status() != WL_CONNECTED) )<br>  {<br>    connectToWifi();<br>  }<br>  printLocalTime();<br>  struct tm timeinfo,timeinfonew;<br>  if(!getLocalTime(&amp;timeinfo)){<br>    Serial.println(&quot;Failed to obtain time&quot;);<br>    return;<br>  }<br>  int hour = timeinfo.tm_hour;<br>  int minute= timeinfo.tm_min;<br>  int sec= timeinfo.tm_sec;<br>  Serial.print(&quot;Hour:&quot;);<br>  Serial.println(hour);<br><br>  Serial.print(&quot;Minute:&quot;);<br>  Serial.println(minute);<br><br>  <br>  Serial.print(&quot;Temperature: &quot;);<br>  <br>  // Convert raw temperature in F to Celsius degrees<br>  float cpu_temp = (temprature_sens_read() - 32) / 1.8 ;<br>  Serial.print(cpu_temp);<br>  <br>  Serial.println(&quot; C&quot;);<br>  if(Blynk.connected())<br>  Blynk.virtualWrite(V2, cpu_temp);<br>  <br>  if ((hour &gt; 5 ) &amp;&amp; (hour &lt; 22))<br>  {<br>  Serial.println(&quot;Enabling the Relay Trigger&quot;);<br>  digitalWrite(LED_BUILTIN, HIGH);<br>  digitalWrite(RELAY_PIN, HIGH);<br>  digitalWrite(BUZZER_PIN,HIGH);<br>  if(connectToBlynk())<br>  Blynk.virtualWrite(V6, &quot;Watered&quot;);<br>  Blynk.run();<br><br>  char timeStringBuff[50]; //50 chars should be enough<br>  strftime(timeStringBuff, sizeof(timeStringBuff), &quot;%A, %B %d %Y %H:%M:%S&quot;, &amp;timeinfo);<br>  //print like &quot;const char*&quot;<br>  Serial.println(timeStringBuff);<br><br>   <br>  delay(180000);<br>  if(!getLocalTime(&amp;timeinfonew)){<br>    Serial.println(&quot;Failed to obtain time&quot;);<br>    //return;<br>  }<br>   char timeStringBuffStopTime[50]; //50 chars should be enough<br>   strftime(timeStringBuffStopTime, sizeof(timeStringBuffStopTime), &quot;%A, %B %d %Y %H:%M:%S&quot;, &amp;timeinfonew);<br>  //print like &quot;const char*&quot;<br>  Serial.println(timeStringBuffStopTime);<br><br>    Serial.print(&quot;Watered Duration:&quot;);<br>    int WateringDuration = timeinfonew.tm_min-timeinfo.tm_min;<br>    digitalWrite(LED_BUILTIN, LOW);<br>    digitalWrite(RELAY_PIN, LOW);<br>    digitalWrite(BUZZER_PIN,LOW);<br><br>     if(WiFi.status() != WL_CONNECTED)<br>     connectToWifi();<br>   <br>    if(WiFi.status() == WL_CONNECTED)<br>    {<br>      Serial.println(&quot;Connected to Internet&quot;);<br><br>      if (connectToBlynk() &gt; 0)<br>      {<br>        Serial.println(&quot;Connected to Blynk&quot;);<br>      //while (Blynk.connect() == false) {}<br>      Blynk.run();<br>      Blynk.virtualWrite(V5, timeStringBuff);<br>      Blynk.virtualWrite(V7, timeStringBuffStopTime);<br>      Serial.println(&quot;Values updated&quot;);<br>      Blynk.run();<br>      <br>      }<br>      else<br>      {<br>        Serial.println(&quot;Not connected to Blynk&quot;);<br>  <br>      }<br>    <br>    //Blynk.virtualWrite(V7, WateringDuration);<br><br>    }<br>    else<br>    {<br>      Serial.println(&quot;Not connected to Internet&quot;);<br><br>    }<br>     <br>    Serial.println(WateringDuration);<br> <br>    }<br>  else<br>  {<br>    if(Blynk.connected())<br>    Blynk.virtualWrite(V6, &quot;Exception Hours&quot;);<br>  <br>  }<br><br>//  int Delta = 0;<br>//  if(PreviousMinimumFreeMemory &gt;0)<br>//  Delta=PreviousMinimumFreeMemory- ESP.getMinFreeHeap();<br>//  else<br>//  Delta = ESP.getMinFreeHeap();<br>  <br>  PreviousMinimumFreeMemory = ESP.getMinFreeHeap();<br>  <br>  Blynk.virtualWrite(V8, (PreviousMinimumFreeMemory));<br><br>  Serial.println(&quot;Done.&quot;);<br>  //while (Blynk.connect() == false) {}<br>  Blynk.run();<br><br>  delay(20000);<br>  //esp_deep_sleep_start();<br>}<br>int connectToWifi()<br>{<br>  WiFi.begin(ssid, pass);<br>  int number_retry = 0;<br>  while (WiFi.status() != WL_CONNECTED) <br>  {<br>    Serial.print(&#39;.&#39;);<br>    delay(1000);<br>    number_retry+=1;<br>    if(number_retry &gt;=10)<br>    <br>   {<br>       Serial.println(&quot;Did not find internet hence resuming without internet.&quot;);<br>       internetConnectedState =0;<br>      return internetConnectedState;<br>   }<br>  }<br>  internetConnectedState = 1;<br>  Serial.println(&quot;Connected to Internet..&quot;);<br>  return internetConnectedState;<br>  <br>  }<br>void setup()<br>{<br>  // Debug console<br>  Serial.begin(115200);<br>  <br>  esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts<br>  esp_task_wdt_add(NULL); //add current thread to WDT watch<br><br>  pinMode (LED_BUILTIN, OUTPUT);<br>  pinMode (RELAY_PIN, OUTPUT);<br>  pinMode(BUZZER_PIN, OUTPUT);<br>  <br>  pinMode (FAN_PIN, OUTPUT);<br>  <br>  digitalWrite(RELAY_PIN, LOW);<br>  <br>  //Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);<br>  <br>  if (!WiFi.config(local_IP, gateway, subnet,dns,dns )) {<br>    Serial.println(&quot;STA Failed to configure&quot;);<br>  }<br>  connectToWifi();<br>  if(WiFi.status() == WL_CONNECTED)<br>  Blynk.config(BLYNK_AUTH_TOKEN);<br>  // You can also specify server:<br>  //Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, &quot;blynk.cloud&quot;, 80);<br>  //Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, IPAddress(192,168,1,100), 8080);<br>   <br>  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);<br>  //while (Blynk.connect() == false) {}<br>  <br>  printLocalTime();<br>  if(connectToBlynk())<br>  Blynk.virtualWrite(V6, &quot;Device Started&quot;);<br>  Blynk.run();<br>  delay(5000);<br>  // Setup a function to be called every second<br>  //timer.setInterval(150000L, myTimerEvent);<br>  timer.setInterval(SLEEP_TIMER_INTERVAL, myTimerEvent);<br>  timerFAN.setInterval(1000*300, myTimerEventForFAN);<br>  myTimerEvent();<br>  <br> <br>  //esp_sleep_enable_timer_wakeup(SLEEP_INTERVAL);<br><br>}<br><br>int connectToBlynk()<br>{<br>  int numberofRetries =0;<br>  if(WiFi.status() != WL_CONNECTED)<br>  {<br>    if (connectToWifi() &lt; 1 )<br>      {<br>       return 0;<br>      }<br>   <br>  }<br><br>  while (Blynk.connect() == false) <br>   {<br>          numberofRetries++;<br>            if (numberofRetries &gt;=10)<br>            {<br>               Serial.println(&quot;Connection to Blynk FAILED..&quot;);<br><br>              return 0;<br>            }<br>    }<br>      <br>  if(Blynk.connected())<br>       {<br>          Serial.println(&quot;Connected to Blynk..&quot;);<br><br>          return 1; <br>       } <br>       <br>  return 0;<br>}<br><br>void loop()<br>{<br>  Blynk.run();<br>  timer.run();<br>  timerFAN.run();<br><br>  esp_task_wdt_reset();<br><br>  // You can inject your own code or combine it with other sketches.<br>  // Check other examples on how to communicate with Blynk. Remember<br>  // to avoid delay() function!<br><br></pre><p><strong>Significance of Automated Irrigation in Agriculture.</strong></p><p>Recognizing the pivotal role water plays in agriculture, we’ve come to appreciate the significance of embracing automated irrigation solutions at home. As we explored ways to reduce our water footprint, we opted for the efficient method of automated irrigation. This innovative technique has allowed us to conserve water while ensuring optimal hydration for our plants. By incorporating automated irrigation, we not only address the core issue of water usage but also contribute to sustainable agriculture practices, emphasizing the importance of water conservation in our daily lives and broader agricultural endeavors.</p><p><strong>Weather-Based Irrigation Systems-Future plans.</strong><br> <br>Future plans involve implementing advanced weather-based irrigation systems to optimize water conservation. These systems will intuitively sense the moisture content of a few plants and adjust watering schedules accordingly, ensuring our plants receive precise amounts of water. By eliminating unnecessary irrigation during favorable weather, we aim to enhance efficiency and contribute to sustainable water management practices. This innovative approach aligns with our commitment to environmental stewardship and represents a proactive step towards resource conservation in our cultivation practices.</p><p><strong>Summary of Key Takeaways.</strong></p><p>Crucially, water conservation is vital for both large-scale agriculture and personal gardening efforts. Introducing technology, such as smart sensors and IoT, elevates the efficiency of sustainable farming practices. Implementing automated watering systems, featuring smart controllers and weather-based irrigation, optimizes water usage. Additionally, strategic water management includes rainwater harvesting and recycling to curtail waste. This user-friendly approach empowers anyone to adopt sustainable farming practices and make a positive impact.<br> <br>This is how we are planning to start our sustainable farming, how are you planning to start yours?!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9386a33a80c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to enhance your old photos using GFP-GAN?]]></title>
            <link>https://medium.com/@abypaulvarghese/how-to-enhance-your-old-photos-using-gfp-gan-d5a64fd99513?source=rss-70147804920a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a64fd99513</guid>
            <category><![CDATA[blur-removal]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[gfp-gan]]></category>
            <category><![CDATA[image-enhancement]]></category>
            <category><![CDATA[restore-old-photos]]></category>
            <dc:creator><![CDATA[Aby Varghese]]></dc:creator>
            <pubDate>Tue, 19 Apr 2022 15:52:02 GMT</pubDate>
            <atom:updated>2022-04-19T15:54:54.978Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to enhance your old photo using GFP-GAN?</strong></h3><p>Improve the resolution and clarity of the images using GFP-GAN</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7SRa3xXwklVcIG9b" /><figcaption>Photo by <a href="https://unsplash.com/@rvignes?utm_source=medium&amp;utm_medium=referral">Romain Vignes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How many old photos do you have in your home that were taken from a film camera? Yes, I’m talking about the ones taken when you were a kid, your parents were teenagers or of your grandparents who have long passed away.</p><p>What comes to your mind when you come across such an old, pixelated and noise-filled photo? Don’t you wish to revive it and make it look like it was taken with a digital camera?</p><p>I used to wish that too. So, I went hunting on the internet and found a gem!</p><p>It is really a useful method using GFP-GAN.</p><h3>What does the GFP-GAN do?</h3><p>You probably have guessed what the library does. Yes, it restores and refines any low-quality face image into a high-resolution image. You can scan any old photo and enhance its quality. But it’s not just the old photos it can enhance but blurred ones too.</p><p>Many times, we end up taking a blurred image of a person only to realize it later. You might not be able to get the same person or same background to take another shot. Imagine taking a group photo with your friends on a trip. Almost always someone moves their head a little bit at the right time when the photo is clicked. Of course, you can take another shot — only if you realize the blurred face then and there itself.</p><p>Imagine you taking a selfie with your favorite celebrity when you run into them. I’m sure they won’t have the time to pose for another photo just because your hands were shaking with all the excitement!</p><h3>Why should you use the GFP-GAN library?</h3><p>Now that you have an idea of what you can do with the library, let’s see what other situations can you use it in:</p><p>Like I said before, we all have some old, aged photos lying around in our houses. You might not have their original negatives and the only copy you have is starting to wither. You can scan it and store it in digital format but the scanned copy will look the same. It might have a yellowish tint. Or if it is a damaged photo, it will have some white spots or lines.</p><p>With the GFP-GAN library, you can not only restore it but enhance its quality and resolution too. You will now be able to see how beautiful your grandmother was at her young age!</p><p>If your old photos are not yet damaged, they will be in the coming years. It’s better that you start scanning them now so that you can store them digitally. And if you enhance them, you can reprint and frame them at a bigger size than they originally were.</p><p>Also, it’s not only some old photos. Often, we take photos in poorly lit areas or with a fingerprint mark on the mobile camera lens. You end up with a blurred image. You can also enhance a photo that you took with an old phone or old digital camera with a lower resolution.</p><p>To fix all these problems, all you have to do is use the image enhancement library, GFP-GAN.</p><h3>What is image enhancement?</h3><p>Oh, are you wondering what exactly is image enhancement?</p><p>Let me explain that first.</p><p>Image enhancement is a process where you digitally improve an image by changing certain parts of it or the entire image using a tool or software. You can make these changes with tools like filters, image editors and so on.</p><p>You might have already done things like changing a colour image to black and white or sepia, changing its contrast or brightness, etc. Such minor changes are also a form of image enhancement.</p><p>If you want graphical design changes to an image, you need advanced digital image processing tools. These are tools like Photoshop, Procreate and others. But these tools are not enough for removing blurriness or restoring old photos. That is where GFP-GAN comes in.</p><h3>What is the GFP-GAN?</h3><p>Here, GFP stands for Generative Facial Prior. It is a GAN architecture designed by researchers Xintao Wang, Yu Li, Honglun Zhang and Ying Shan in their paper Towards Real-World Blind Face Restoration with Generative Facial Prior. GFP is a framework specifically designed to improve the quality of human faces in old, damaged, and low-resolution photos.</p><h3>What is the GAN?</h3><p>GAN stands for Generative Adversarial Network and is a machine learning framework. It’s a framework that has a wide range of applications apart from image restoration like art generation, astronomical and other science simulations, improvisation of astronomical images, human image synthesis for animations and movies and so on.</p><h3>How to enhance your image?</h3><p>Enough of theory. Now let me tell you how you can enhance an image.</p><h3>Prerequisites to install</h3><p>First, you need to install OpenCV 4.5. Here’s a link that gives you step by step instructions on how to install OpenCV 4.5 with CUDA 11.2 in Ubuntu 20.04</p><p><a href="https://gist.github.com/raulqf/f42c718a658cddc16f9df07ecc627be7">https://gist.github.com/raulqf/f42c718a658cddc16f9df07ecc627be7</a></p><p>Didn’t work or don’t have Ubuntu? No problem. Check out the NVIDIA CUDNN Documentation. It also gives you the procedure to install it on Windows and other popular operating systems.</p><p><a href="https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html">https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html</a></p><p>Done? Let’s move on to the next step.</p><h3>Installing GFP-GAN</h3><p>Now that you have installed the necessary libraries in your system, you can proceed to use the GFP-GAN face restoration program.</p><p>You can get the open-source program here:</p><p><a href="https://github.com/TencentARC/GFPGAN">GitHub - TencentARC/GFPGAN: GFPGAN aims at developing Practical Algorithms for Real-world Face Restoration.</a></p><p>This is a clean version of GFPGAN, which doesn’t need any customised CUDA extensions.</p><ol><li>Clone repo</li></ol><blockquote>git clone <a href="https://github.com/TencentARC/GFPGAN.git">https://github.com/TencentARC/GFPGAN.git</a></blockquote><blockquote>cd GFPGAN</blockquote><p>2. Install dependent packages</p><blockquote># Install basicsr — <a href="https://github.com/xinntao/BasicSR">https://github.com/xinntao/BasicSR</a></blockquote><blockquote># We use BasicSR for both training and inference</blockquote><blockquote>pip install basicsr</blockquote><blockquote># Install facexlib — <a href="https://github.com/xinntao/facexlib">https://github.com/xinntao/facexlib</a></blockquote><blockquote># We use face detection and face restoration helper in the facexlib package</blockquote><blockquote>pip install facexlib</blockquote><blockquote>pip install -r requirements.txt</blockquote><blockquote>python setup.py develop</blockquote><blockquote># If you want to enhance the background (non-face) regions with Real-ESRGAN,</blockquote><blockquote># you also need to install the realesrgan package</blockquote><blockquote>pip install realesrgan</blockquote><p>Now lets download the pre trained model</p><blockquote>wget <a href="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth">https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth</a> -P experiments/pretrained_models</blockquote><h3>Results?</h3><p>Let me first show you my results. Below are two sets of images of Dennis Ritchie, the inventor of the programming language C.</p><figure><img alt="Input image on the left side and the result on the right side" src="https://cdn-images-1.medium.com/max/940/1*O5Q9fJyq9Hw1sH01hl32-w.png" /><figcaption>The input image is on the left side and the output image is on the right side</figcaption></figure><p>Here is another image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*71rzOg0NWSvZwB40u_p-AA.png" /><figcaption>The input image is on the left side and the output image is on the right side</figcaption></figure><p>As you can see, in both the images the left ones are pixelated, noisy and a little bit blurred too. The right ones are crisp and look as if they were taken using a digital camera or a mobile phone. But they are not.</p><p>The left ones are the input image to the GFP-GAN and the right ones are the output images after processing. You can see a clear difference in terms of the image quality in the output images.</p><p>Below are the <strong>specifications</strong> of the test environment:</p><p>● Graphics Processor: NVIDIA GeForce GTX 1650</p><p>● CUDA Cores:896</p><p>● Total Memory:4096 MB</p><p>● CPU: AMD RYZEN 4000 series.</p><p>Do you want to know how long they took? Here are the <strong>processing times</strong>:</p><p>● 1st image: 4.0337 seconds</p><p>● 2nd image: 3.3261 seconds</p><h3>Disadvantages:</h3><p>Even though GFP-GAN is a very useful library, it is not perfect. Because when I tried with other images, I observed that the generated image is not always accurate.</p><p>Here is one such result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*pLvaIyu-ZyenaM1u183uPw.png" /><figcaption>The input image is on the left side and the generated output image is on the right</figcaption></figure><p>Here, the generated face of the kid does not look realistic. Also, the model has generated some grey hair. It might have happened that the grey hair come from the lighting in the source photo however it is very evident that the generated image has slightly changed the identity itself.</p><h3>Conclusion</h3><p>So, that was how I found a way to enhance an old image. All thanks to the researchers Xintao Wang, Yu Li, Honglun Zhang and Ying Shan for developing GFP-GAN.</p><p>Although some images may not turn out as you expect, it is pretty good at face restoration and color enhancement. It is still worth spending some time to enhance all the old, damaged and faded photos lying around your house.</p><p>What do you think about GFP-GAN? Have you ever tried something like this before? Let me know in the comments below</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a64fd99513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Video analytics at the edge]]></title>
            <link>https://medium.com/data-science/video-analytics-at-the-edge-1c1e05c5fd5a?source=rss-70147804920a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c1e05c5fd5a</guid>
            <category><![CDATA[smart-camera]]></category>
            <category><![CDATA[edge-analytics]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[video-analytics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Aby Varghese]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 12:48:16 GMT</pubDate>
            <atom:updated>2021-06-22T05:09:49.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use Raspberry PI and Intel NCS to detect human from CCTV IP cameras</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBX2Tbib5IUcoKrRz9S0Rw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@logz05?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nick Loggie</a> on <a href="https://unsplash.com/s/photos/cctv-camera?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I have recently installed a CCTV system at my home. It consisted of 4 IP cameras. I wanted them to be a bit more smarter. Instead of looking at the CCTV footage always, it would be good to get a notification if there is human detected by any of the cameras. This is a really cool stuff. I thought it would be really good if I get an alarm in my Telegram if any of the camera detect a motion. Though I started it for fun, I had a great learning. Fundamentally it enables video analytics at the edge without needing a cloud. I am here to share my learning and eager to learn from you if there are ways to optimize.</p><h3>Objective</h3><p>I have 4 different IP cameras that stream 720P videos at 25FPS. I have a raspberry pi sitting idle and have got an Intel Movidius neural compute stick (ie first generation of NCS ). I wanted the Raspberry PI and NCS to perform the human detection and send me the notification in telegram when the camera detects a person. There were few things that I consider very important during the build, which are</p><p>1. I should be able to run the application almost 24/7 , that means the code should be efficient. The CPU utilization must be as minimum as possible so that the PI’s temperature is under control.</p><p>2. I should get the notification almost instantaneously. The highest priority was that the human detection should complete as soon as it happens.</p><p>3. The notification should contain an image so that I can understand the context of the alert (who was the person).</p><p>Let me tell you in advance, the item 1, and 2 were much harder than I thought.</p><h3>Project start:</h3><p>I thought it is an easy task assuming Raspberry pi can get the video frame from each of the camera and NCS can perform the human detection. However, it was not so easy.</p><p>As usual, I started with plain OpenCV code to read the video RTSP stream a single camera and see how it works.</p><pre>cap = cv2.VideoCapture(“RTSP URL of the IP Camera”)<br><br> <br><br>while(True):<br><br>    ret, frame = cap.read()<br><br>    cv2.imshow(&#39;frame&#39;,frame)<br><br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br><br>        break<br><br> <br><br>cap.release()<br><br>cv2.destroyAllWindows()</pre><p>However few things were not working as I expected. First and foremost, there were huge delay in getting the frame in real time. Ie even if there are no processing (human detection) there was a delay of around 5 to 10 seconds and in some cases, it went to 40 seconds within couple of minutes of running the application. The CPU utilization reached 100% immediately. This is the point where I realized this is much complex than I thought. So, I had to go back to the drawing board to see what would be the best way to solve this problem.</p><p>I observed that this solution does not require to process each and every frame from the camera during my analysis. We absolutely don’t need to analyze 25 frames that are generated in a second. This is one of the primary principles that I used in my design and I came up the following design. What parameter will help us to define the number of frames that the system can process will be discussed later.</p><h3>Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAuSTn208WiwcVjry28iAg.jpeg" /><figcaption>Image by author</figcaption></figure><p>As you may notice, the idea is to capture N number of frames from each of the camera in every X seconds. This was not the only reason which made the system work efficiently. The solution made use of the hardware acceleration available in Raspberry pi so that the CPU utilization is very minimal. This will be detailed when I describe about GStreamer. The reason why the number of frames and the duration are variable is that it is purely based on the processing power of the hardware that is used for processing the frames. As per my knowledge, the first version of Intel NCS can perform less number of inferences. As you can imagine, the diagram clearly shows the bottle neck in the processing engine since it has to process all the frames. Since my plan to make use of an existing Intel NCS, I had to adjust these parameters according to the capabilities of the NCS.</p><p>As a starting point, I decided to capture one frame in every one second from each of the camera. This seems to be reasonable to me. Since it is not practically possible for a person to go past the camera viewing area in less than a second. However there is a possibility that the processing engine might fail to detect the object, but that is a separate topic which we will look later.</p><p>I realized that it is difficult to specify the frame number(s) / second that I want to capture when I am using OpenCV. So explored and found out that there are possibly two approaches to solve this problem . One is GStreamer and another is FFMPG. So I decided to explore the first option GStreamer further.</p><p>I found GStreamer is extremely powerful but complex due to the lack of documentation / examples. So I started exploring few tutorials in youtube and I found them very useful. I have mentioned the links that helped me to study about GStreamer in the Reference section. I am sure it will help you too.</p><h3>Installation and Setup</h3><p>The source code for this experiment can be found here :</p><p><a href="https://github.com/abypaulvarghese56/Edgevisionpi">abypaulvarghese56/Edgevisionpi</a></p><p>The first step for me was to install GStreamer in Raspberry PI. This was fairly straight forward.</p><pre>sudo apt-get install gstreamer1.0-tools</pre><p>The next step was to install Intel OpenVino toolkit for raspberry PI. This was necessary since the processing engine was Intel NCS. I had to install a version of OpenVINO that is supporting intel NCS since the latest versions of OpenVINO only support the Intel NCS 2. Please follow the link below link and install OpenVINO based on the NCS that you have.</p><p><a href="https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_raspbian.html">Install OpenVINO™ toolkit for Raspbian* OS - OpenVINO™ Toolkit</a></p><p>Other libraries include:</p><pre>pip install telepot<br>pip install viztracer<br><br>sudo apt-get install pkg-config libcairo2-dev gcc python3-dev libgirepository1.0-dev<br>sudo apt-get install python3-gi<br><br>pip install gobject PyGObject</pre><p>The next step is to create the GStreamer pipeline. As I mentioned earlier, it is very powerful tool. Gstreamer is configured by the use of pipelines, which are a series of commands specifying where to get video from, how to process and encode it, and then where to send it out.</p><p>Lets have a look at the pipeline that I have created.</p><pre>pipelinestring = &quot;rtspsrc location={0} name=m_rtspsrc ! rtph264depay ! h264parse ! v4l2h264dec capture-io-mode=4 ! video/x-raw ! v4l2convert output-io-mode=5 capture-io-mode=4    ! video/x-raw, format=(string)BGR, width=(int)640, height=(int)480 ! videorate ! video/x-raw,framerate=1/1 ! appsink name=m_appsink sync=false&quot;</pre><p>Lets see the purpose of each element.</p><p>rtspsrc location={0} — The location is the RTSP url of the camera stream.</p><p><strong>rtph264depay </strong>— Extracts H264 video from RTP packets.</p><p><strong>v4l2h264dec</strong>- This is an interesting one . This tells the Raspberry PI to decode the H264 using the GPU. Remember there is an alternative which uses the CPU to decode. It is avdec_h264. Using avdec_h264 might work if we try to decode from only one camera. However since our objective is to capture from 4 cameras, it is very essential for us to offload it to the GPU.</p><p>Lets look into the parameters,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*TQDzgElbo7qL91eU7XAQ5Q.png" /></figure><blockquote>Offloading the video decoding to GPU is a critical step towards our goal of minimizing the usage of CPU.</blockquote><p><strong>v4l2convert </strong>— This is letting the system know to convert the frame using the GPU instead of the CPU. There is a CPU equivalent which is video convert. This is again a CPU intensive process so we should be using v4l2convert to make use of the hardware acceleration offered by the Raspberry PI. We are doing few conversions here, they are</p><p>converting the source format into BGR. The frame size is reduced to 640x480 (from the original (720P). The documentation for v4l2convert says that there is an option for controlling the frame rate using v4l2convert itself. However I couldn’t make it work. Please let me know if any of you have made it work, I would be glad to hear. I had to use another videorate to control the frame rate since I couldn’t make v4l2convert control the frame rate.</p><p><strong>videorate </strong>— This will help us to control the framerate that we want to capture in the application. Here in our case we want to capture only 1 frame in a second from a camera. So it will be framerate=”1/1” . Assume we want to capture only one frame in two seconds then the framerate will be “1/2”. Incase if we want to capture 5 frames in a second, the frame rate will be “5/1”</p><p>Now the idea is to run the video capture application using multiprocessing to make use of the different cores of Raspberry PI. The main program will kick off a separate process for each of the camera.</p><p>The rest of things are fairly straight forward. Once the frame is captured, it is converted to OpenCV format and pushed into a Queue. Currently this conversion is done using python code, kindly let me know if there is way to handle it within GStreamer pipeline. I am assuming there will be, but I have not investigated. It can further reduce the CPU usage if we can handle it within GStreamer pipeline as per my knowledge. Since we have 4 different cameras, there will be 4 different queues. The queues are using TCP protocol, because it will help us to distribute the load in future if we want this system to work on multiple hardware. ie we can scale out the processing server based on our needs and increase the frame rate or interval of capture or add more cameras. Probably we shall optimize it for distributed environment in the next release.</p><p>In the main_prgall.py (line number 27), you will have enter the RTSP URL of your streams</p><pre>self.camlink1 = &#39;rtsp://&lt;username&gt;:&lt;password&gt;@192.168.1.2:554/cam/realmonitor?channel=1&amp;subtype=0&amp;unicast=true&amp;proto=Onvif&#39; #Add your RTSP cam link</pre><p>and add the rest of the stream URLs based on your environment.</p><blockquote>You can consume GStreamer pipeline from OpenCV. The Opencv needs to build with GStreamer support.</blockquote><p><strong>Processing Server</strong></p><p>The idea is very straight forward, grab the frame from the Queues (4 queues) and push it to the intel NCS. The queue works using PUB / SUB model here. The camera is the PUB and the process server is the SUB. We shall move a frame to another queue if NCS detects a human in the frame.I have used the person detection retail 013 model from the intel model zoom. The details of the model can be found here:</p><p><a href="https://docs.openvinotoolkit.org/2021.2/omz_models_intel_person_detection_retail_0013_description_person_detection_retail_0013.html">person-detection-retail-0013 - OpenVINO™ Toolkit</a></p><p>It is essential that you should use the model that is compactible with your device. If you have NCS 2, then you should use the model that support NCS2.This is a model that can detect person in the video frame. It accepts the input frame of size height 320 and width 544</p><p><strong>Communication engine</strong></p><p>This is a very straight forward component. It gets the processed data from the Queue and stores the image into the local directory. It also connects with the Telegram bot and sends out a notification with the image attached.</p><blockquote>The Bot Key and user ID is removed from the source code. You will have to insert your own Telegram bot Key and user ID</blockquote><h3><strong>Result</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2zcJvp4T-lhrJtYqASrbw.jpeg" /></figure><blockquote>You can see from the image that the frames are processed almost realtime. During my testing, I found that all the frames were able to process in less than 2 seconds. ( detect motion in less than 2 seconds ). There might be a slight delay in the Telegram bot sending the image, but that is based on your Internet connectivity . However, I found it was negligible in almost all the cases.</blockquote><p><strong>CPU Consumption</strong></p><p>The CPU consumption was around 30–35% which is okay considering the fact that it is processing the videos from 4 different streams in every second. The below image shows the CPU consumption and the temperature reported by raspberry pi.</p><p>I have found another way in which CPU utilization can be reduced. That is not in the python scripts, but in the CCTV itself. Most of the IP cameras supports multiple streams. ie one Mainstream ( with High quality resolution and frame rate) and sub stream with reduced resolution(640x480 in my case). The following screenshot shows the setting in my camera web interface</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyJDIujwN3cm_DC7XOT_1A.png" /></figure><p>The following diagram shows the CPU utilization and temperature when connected to sub stream</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*ISm-bZmGmXC_HXIqoJPxRw.png" /></figure><blockquote>As you may notice , the overall cpu utilization is between 16–22% that seems to be very reasonable. Since the heavy lifting was done the GPU, the system is able process multiple streams with less CPU usage in less than 2 seconds</blockquote><h3>Conclusion</h3><p>Raspberry PI is a great platform. You will be able to find plenty of libraries and support .It is relatively cheap and efficient. The Intel NCS 1 does its duty. Probably the Intel NCS2 will be able to perform more number of inferences because it is advertised as much better in terms of performance. I have not got a chance to test the application in NCS 2 since I dont have one. I would really love to hear If any of you would like to test the script in NCS2 and report the performance . Having said, it just happened that I had both NCS1 and Raspberry PI for my experimenting. This might not be the best platforms if you are starting from scratch from a cost perspective. The RPI will cost around 4K INR and NCS costed me around 8K INR. I am curious to know how Nvidia’s Jetson Nano 2GB is. It has much better performance than NCS2 and dont require another SBC like PI. The cost is around 5K INR. Probably I shall cover it in my next update.</p><p><strong>References</strong></p><p><a href="https://github.com/sahilparekh/GStreamer-Python">https://github.com/sahilparekh/GStreamer-Python</a> — This is great repo that shows how to fetech RTSP streams in OpenCV. I have extended this sample in my project and the credit goes to the respective owner.</p><p><a href="https://www.youtube.com/watch?v=HDY8pf-b1nA">https://www.youtube.com/watch?v=HDY8pf-b1nA</a> — This is a great place to start learning about GStreamer . This has really helped me to learn about GStreamer.</p><p><a href="http://lifestyletransfer.com/how-to-use-gstreamer-appsrc-in-python/">http://lifestyletransfer.com/how-to-use-gstreamer-appsrc-in-python/</a> — This is great place to learn about advanced Gstreamer concepts . A great set of working examples with great explanations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c1e05c5fd5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/video-analytics-at-the-edge-1c1e05c5fd5a">Video analytics at the edge</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>