<?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 Pamudu on Medium]]></title>
        <description><![CDATA[Stories by Pamudu on Medium]]></description>
        <link>https://medium.com/@pamudu1111?source=rss-8693d059d7ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*71KgA0pqWPnkNehB</url>
            <title>Stories by Pamudu on Medium</title>
            <link>https://medium.com/@pamudu1111?source=rss-8693d059d7ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:45:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pamudu1111/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[The Remote Work Paradox: A Quantitative Analysis of Professional Work-Life Balance in 2025]]></title>
            <link>https://medium.com/@pamudu1111/the-remote-work-paradox-a-quantitative-analysis-of-professional-work-life-balance-in-2025-b35912fd240e?source=rss-8693d059d7ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35912fd240e</guid>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[hybrid-work]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Pamudu]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 17:54:05 GMT</pubDate>
            <atom:updated>2025-12-22T02:03:46.266Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Flexibility was supposed to be the answer to burnout. But new data suggests that while remote workers have reclaimed their time, they might be losing their connection.</strong></p><p>By <strong>Pamudu Ranasinghe</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_9sgLSPuxxVo7ZvwyPpDg.png" /></figure><p>Since the global shift in 2020, flexible work has evolved from a pandemic necessity to a standard expectation. By 2025, we’ve settled into new rhythms: some of us are fully remote, some are back in the office, and many are navigating the hybrid middle ground.</p><p>But is “flexibility” actually fixing our work-life balance?</p><p>To answer this, I conducted a quantitative analysis of 50 professionals across various sectors — from IT to Healthcare — between <strong>June and July 2025</strong>. This research was conducted as part of my <strong>Master’s project in Statistical Inference</strong>.</p><p>A Note on the Methodology:</p><p>This article presents a simplified overview of my findings to make them accessible to a broader audience. The full research paper contains deeper statistical models, extensive literature reviews, and detailed methodological breakdowns that are beyond the scope of this summary.</p><p>Here is what the data revealed.</p><h3>1. The Remote Trade-Off: Better Balance, Higher Isolation</h3><p>The most striking finding in the data was a clear paradox for the fully remote workforce.</p><p>On paper, remote workers are living the dream. They reported the lowest levels of <strong>Work Interference with Personal Life (WIPL)</strong> — meaning work was less likely to intrude on their personal time compared to their on-site peers. Without the commute and office distractions, they have reclaimed their evenings.</p><p>However, this freedom comes with a hidden cost: <strong>Social Disconnection</strong>.</p><p>My analysis found that fully remote workers reported markedly higher social disconnection scores than hybrid or on-site employees. While they aren’t stressed about the commute, they are missing out on the informal support networks — the “water cooler moments” — that bind a team together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*7uV5jrsl6d4U3xtsBcwzuA.png" /><figcaption>Figure 1: Radar chart of work-life balance dimensions by work arrangement. The chart should show remote workers having low work interference but high social disconnection.</figcaption></figure><p><em>Above: Note how the remote group (green line) shows low interference but spikes significantly in Social Disconnection compared to Hybrid and On-site groups.</em></p><h3>2. Hybrid Work: The “Safe” Middle Ground?</h3><p>Hybrid work is often marketed as “the best of both worlds.” In my study, hybrid workers did indeed sit squarely in the middle. They reported less social isolation than remote workers but faced more work-life interference than the fully remote group.</p><p>Interestingly, the difference in “work interference” levels between hybrid and on-site workers wasn’t statistically significant in this sample. This suggests that simply allowing employees to work from home two days a week doesn’t automatically solve burnout if the workload and culture remain the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*ExVAi4Jhpp3IjPRP1CF80w.png" /><figcaption>Figure 2: Mean WIPL scores by work arrangement. A bar chart showing On-site having the highest interference, followed by Hybrid, with Remote having the lowest.</figcaption></figure><p><em>Above: Remote workers report the lowest interference, while Hybrid and On-site levels remain higher.</em></p><h3>3. The “Switch Off” Button is Broken</h3><p>One of the modern worker’s biggest complaints is the inability to “switch off” at the end of the day. Is this because we are working from our living rooms?</p><p>Surprisingly, my data suggests that <strong>where</strong> you work matters less than <strong>how much</strong> you work.</p><p>A dominance analysis revealed that “Work Interference with Personal Life” (essentially, workload intensity and boundary intrusion) accounted for nearly <strong>60% of the variance</strong> in a person’s ability to switch off.</p><p>In other words, you can be fully remote, but if your company culture expects instant replies at 8 PM, your location won’t save you. The difficulty of switching off is driven mainly by work interference, not by the arrangement type itself.</p><h3>4. The Industry Divide</h3><p>Finally, we have to acknowledge that “flexibility” isn’t distributed equally. The study highlighted a strong association between departments and working hours.</p><ul><li><strong>Healthcare</strong> employees were heavily tied to rotating shifts.</li><li><strong>IT and Engineering</strong> respondents overwhelmingly favored flexible schedules.</li><li><strong>Customer Support</strong> roles were often locked into fixed time-zone shifts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*2U44lUEOs6fdTX2o3SkCUw.png" /><figcaption>Figure 3: Heat-map of standardized residuals showing association between department and working hours. It highlights clusters like Healthcare with rotating shifts and IT with flexible hours.</figcaption></figure><p><em>Above: The heat map highlights distinct clusters, showing that for many industries, “flexible hours” remain a luxury.</em></p><h3>The Verdict</h3><p>So, what is the takeaway for managers and employees in 2025?</p><p>Flexibility is a tool, not a cure-all. My research suggests that while remote work is excellent for reducing life interference, it creates a vacuum of social connection that organizations must actively fill. Conversely, for hybrid and on-site roles, the focus shouldn’t just be on schedules, but on <strong>workload intensity</strong>.</p><p>To truly realize the benefits of flexibility, we need to do more than just let people work from home. We need to curb workload volume, set clear communication boundaries, and find new ways to nurture the social connections we’ve lost.</p><h3>A Look Under the Hood: Adapting the Survey for 2025</h3><p>For this study, I did not simply rely on existing metrics. I realized that traditional scales from the early 2000s could not capture the nuances of the post-pandemic workplace.</p><p>I heavily adapted Hayman’s (2005) Work-Life Balance Scale and <strong>created entirely new questions</strong> to address modern challenges such as AI integration, digital boundary management, and remote social isolation.</p><p>For transparency, the survey used for this analysis was hosted online and can be viewed here: <a href="https://pamudu123.github.io/modern-work-practices-survey/">Modern Work Practices Survey</a>.</p><p><strong>Work Interference with Personal Life (WIPL)</strong></p><p><em>1. My personal life suffers because of my work.<br>2. I feel I have to reply to work messages or e-mails after hours.<br>3. Work is so fast-paced that I cannot fully relax after hours.<br>4. I am unhappy with the amount of time for non-work activities.</em></p><p><strong>Personal Life Interference with Work (PLIW)</strong></p><p><em>5. My personal life drains me of the energy I need for my work.<br>6. Distractions in my home environment during work hours make it difficult to focus.<br>7. Because of personal commitments, I take part less in team communication or meetings.<br>8. I do not spend much time with teammates outside work because of personal matters.</em></p><p><strong><em>Work/Personal-Life Enhancement (WPLE)</em></strong></p><p><em>9. I have enough control over my job to manage both work and personal life well.<br>10. The flexibility my job offers helps me manage personal responsibilities.<br>11. My personal life gives me energy for my job.<br>12. My job helps me feel energetic for my personal life too.</em></p><p><strong>Modern Work Experience</strong></p><p>These items were specifically created for this study to measure the impact of modern tools and remote work environments.</p><p><em>13. AI tools help me work faster and improve my work-life balance.<br>14. I feel pressured to work at the same time as colleagues even when tasks could be done flexibly.<br>15. I feel comfortable talking to my manager if I am overwhelmed or stressed.<br>16. I find it difficult to “switch off” from work at the end of the day when working from home.<br>17. Working remotely makes me feel socially disconnected from colleagues and company culture.<br>18. The digital tools and communication platforms we use help me collaborate effectively with my team.</em></p><p><em>This article is based on the research paper “Work-Life Balance in Flexible Work Arrangements: A Quantitative Analysis of Post-Pandemic Professional Experiences” (2025).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5bKUFmdLvR2vkJgkLTaow.png" /></figure><p>Pamudu Ranasinghe</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35912fd240e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Approach for Generalizable AI Image Detection]]></title>
            <link>https://medium.com/@pamudu1111/technical-report-generalizable-ai-image-detection-8b0d901f3c2a?source=rss-8693d059d7ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0d901f3c2a</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[ai-image-generation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deepfakes]]></category>
            <dc:creator><![CDATA[Pamudu]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 16:50:54 GMT</pubDate>
            <atom:updated>2025-11-30T13:51:34.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfeG-re1yYPgzRIFj9uRYA.png" /></figure><p><strong>Competition:</strong> <a href="https://www.kaggle.com/competitions/detect-ai-vs-human-generated-images/data">Detect AI vs. Human-Generated Images</a></p><h3>1. Introduction: The Core Challenge</h3><p>Take a close look at the cover image. While the subjects appear tangible and alive, they are nothing more than mathematical approximations of reality. None of them exist. This level of photorealism highlights exactly why this task is so difficult<strong><em>: the line between captured light (photography) and generated noise (AI) has effectively vanished to the naked eye.</em></strong></p><p>Initially, I approached this competition as a traditional computer vision classification task, assuming that standard techniques used for objects (like distinguishing cats from dogs) would suffice. However, early experiments revealed that this problem cannot be tackled in the same way. The realization that semantic strategies fail when applied to forensic detection motivated this report and the specialized architectural choices detailed below.</p><p>Detecting AI-generated images is fundamentally different from standard object classification tasks like ImageNet. In traditional tasks, the goal is to identify <strong>semantic content</strong> (e.g., “is this a dog?”). In AI detection, the semantic content is often a distractor.</p><p>The core challenges identified in this competition are:</p><ol><li><strong>Semantic Overfitting:</strong> Standard models tend to memorize “what” is in the image rather than “how” it was generated. For example, if the training data contains many AI-generated astronauts, the model learns “Astronaut = Fake” rather than detecting pixel-level generation artifacts.</li><li><strong>The “Unseen Generator” Problem:</strong> Generative models evolve rapidly (Seedream 4.0, Midjourney v6, DALL-E3, Flux 2, etc.). A detector trained on older artifacts (e.g., Stable Diffusion 1.5) often fails to generalize to newer models unless it targets fundamental signal processing anomalies.</li><li><strong>Preprocessing Destructiveness:</strong> Standard deep learning pipelines resize images (e.g., to 224 x 224). This interpolation smooths out the high-frequency pixel “jitter” and grid artifacts that serve as the primary evidence of AI generation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1-GrZgN1waJty-woq3luw.jpeg" /></figure><h3>2. Preliminary Experiments &amp; Failure Analysis</h3><p>Our initial approach relied on transfer learning using state-of-the-art (SOTA) backbones pre-trained on massive datasets.</p><h3>Attempt 1: ConvNeXt Base (convnext_base.clip_laion2b_augreg_ft_in1k)</h3><ul><li><strong>Model Stats:</strong> ~88.6 Million Parameters.</li><li><strong>Infrastructure:</strong> Kaggle P100 GPU (16GB VRAM).</li><li><strong>Rationale:</strong> ConvNeXt was chosen for its modern CNN architecture that competes with Transformers, utilizing large (7 x 7) kernels to capture global context. We selected the base variant to maximize capacity within the 16GB VRAM limit.</li><li><strong>Results:</strong> The model achieved excellent metrics on the training and validation splits but failed significantly on the public leaderboard (Evaluation Set &lt; 50% Accuracy).</li><li><strong>Analysis:</strong> The model suffered from severe <strong>semantic overfitting</strong>. It essentially memorized the content of the training set. Since the evaluation set likely contained different subjects or unseen generators, the model’s predictions were worse than random guessing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehp2M3aOu5b0GaSKJ1oJ1g.jpeg" /></figure><p><em>The model struggled significantly with bright or white images. It treated the “smoothness” of white backgrounds as a sign of AI generation. Consequently, real photos taken in bright lighting or studios were frequently misclassified as Fake (False Positives).</em></p><h3>Attempt 2: DaViT Small (davit_small.msft_in1k)</h3><ul><li><strong>Model Stats:</strong> ~49.7 Million Parameters.</li><li><strong>Rationale:</strong> To address the slow training of ConvNeXt, we tested the Dual Attention Vision Transformer (DaViT). It trained approximately <strong>5x faster</strong> due to its efficient spatial/channel attention mechanism.</li><li><strong>Results:</strong> Similar to ConvNeXt, it converged quickly during training but demonstrated poor generalization on the unseen dataset.</li><li><strong>Analysis:</strong> Vision Transformers process images in patches (e.g., 16 x 16). This “patchification” breaks the continuity of the pixel grid, effectively masking the subtle frequency artifacts required for forensics.</li></ul><h3>3. Proposed Solution: Multi-Stream Artifact Analysis</h3><p>To solve the generalization problem, we shifted from a “Content-First” approach to an <strong>“Image-Processing-First”</strong> architecture. We designed a custom 3-Stream model that forces the network to analyze specific forensic fingerprints.</p><h3>3.1 Architecture: The Three-Stream Model</h3><p>Instead of one large backbone, we utilized <strong>three lightweight ResNet18 backbones</strong> running in parallel. This fits within the P100 memory constraints while allowing specialized processing for different signal types.</p><p><strong><em>Code: </em></strong><a href="https://github.com/pamudu123/Detect-AI-vs.-Human-Generated-Images"><strong><em>https://github.com/pamudu123/Detect-AI-vs.-Human-Generated-Images</em></strong></a></p><h4><strong>Stream A (</strong> Chroma — CrCb)<strong>:</strong></h4><ul><li><strong>Input:</strong> Cr and Cb Color Channels (No Grayscale/Luminance).</li><li><strong>Goal:</strong> Generative models often exhibit “color bleeding” or statistical inconsistencies in the chrominance channels that are distinct from luminance. By explicitly separating color from brightness, we prevent the model from overfitting to lighting conditions (shadows/highlights) and force it to look for color-space anomalies.</li><li><strong>Backbone:</strong> resnet18d.ra2_in1k (Modified for 2-channel input).</li></ul><p><em>We implemented a custom differential layer to extract Chroma channels on the fly:</em></p><pre>def get_crcb(self, x):<br>    &quot;&quot;&quot;<br>    Extracts Cr and Cb channels from RGB input.<br>    Assumes x is (B, 3, H, W).<br>    &quot;&quot;&quot;<br>    r = x[:, 0, :, :]<br>    g = x[:, 1, :, :]<br>    b = x[:, 2, :, :]<br>    <br>    # Calculate Cb and Cr (using standard coefficients, ignoring offsets for normalized data)<br>    # Cb = -0.1687R - 0.3313G + 0.5B<br>    cb = -0.1687 * r - 0.3313 * g + 0.5 * b<br>    <br>    # Cr = 0.5R - 0.4187G - 0.0813B<br>    cr = 0.5 * r - 0.4187 * g - 0.0813 * b<br>    <br>    # Stack to create (B, 2, H, W)<br>    return torch.stack([cb, cr], dim=1)</pre><ul><li><strong>Example Explanation:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnhkO2n97QNQC0m5ncyhYQ.png" /></figure><p>The AI artifacts are easily detectable here: the trees in the color channels appear as flat, solid silhouettes. Unlike a real photograph, which would retain internal texture and natural sensor grain, the AI has simplified the forest into a detail-free shape and rendered the sky with impossible smoothness.</p><h4><strong>Stream B (Noise — Residuals):</strong></h4><ul><li><em>Residual​=Original​−GaussianBlur(σ=2.0)</em></li><li><strong>Goal:</strong> By subtracting the smooth content of the image, we isolate high-frequency <strong>noise residuals</strong>. This forces the model to ignore the subject (e.g., the dog) and focus on upsampling artifacts.</li><li><strong>Backbone:</strong> resnet18d.ra2_in1k.</li><li><strong>Example Explanation:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFKBexZYj3BrRBkCoqd2ug.png" /></figure><p>The “grain” appears inconsistent and changes based on the object <em>(e.g., heavy texture on the shirt vs. flat walls)</em>. In a real photograph, sensor noise is a uniform that looks the same across the entire image.<br>The patterns on the shirt are mathematically perfect and unusually sharp in the noise map. Real fabric has folds and lighting variations.</p><h4><strong>Stream C (Frequency — Spectral):</strong></h4><ul><li><strong>Input:</strong> Log-Power Spectrum of the FFT (Fast Fourier Transform).</li><li><strong>Goal:</strong> AI generators (GANs/Diffusion) often leave characteristic “checkerboard” grid patterns in the frequency domain that are invisible to the human eye.</li><li><strong>Backbone:</strong> resnet18 (Modified for 1-channel input).</li><li><strong>Example Explanation:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lt0MUXM3n1AbBsl3jAlVg.png" /></figure><p>In a natural photograph, the FFT spectrum usually looks like a cloud that decays smoothly from the center (low frequencies) to the edges (high frequencies). In this image, you can see distinct streaks or “rays” extending far out to the edges.</p><h3>3.2 Data Pipeline Improvements</h3><p>A critical insight was that standard resizing destroys forensic signals.</p><ul><li><strong>The “No-Resize” Rule:</strong> In the train_transform pipeline, we replaced Resize with RandomCrop((512, 512)).</li><li><strong>Reasoning:</strong> Standard resizing algorithms (like Bilinear interpolation) act as low-pass filters, smoothing out the very high-frequency artifacts we need to detect. By using random crops, we input pristine, un-interpolated pixel data into the model.</li><li><strong>Resolution Choice:</strong> We selected 512 x 512 to maximize the receptive field while fitting within GPU memory. However, going higher (e.g., 640 x 640, 1024 x 1024 or full resolution) is strongly recommended if computational resources allow, as larger crops capture longer-range dependencies in the noise patterns.</li></ul><h3>3.3 Curriculum Training Strategy</h3><p>To prevent the model from relying solely on the RGB stream (the easiest path), we implemented a phased “Curriculum” training loop. This strategy aligns with the principle that models should learn “hard” features before “easy” features to prevent shortcut learning.</p><ol><li><strong>Warmup (Epoch 0–3):</strong></li></ol><ul><li><strong>Action:</strong> Train <em>only</em> the classification head; freeze all backbones.</li><li><strong>Why:</strong> The new classification head is initialized with random weights. If we backpropagate immediately through the whole network, the large random gradients can distort the well-tuned pre-trained weights of the backbones (catastrophic forgetting).</li></ul><p><strong>2. Full Tuning (Epoch 4–15):</strong></p><ul><li><strong>Action:</strong> Unfreeze all streams for final optimization.</li><li><strong>Why:</strong> Once the classification head is stabilized, we unfreeze all streams trained in parallel. This allows the model to handle edge cases where artifacts are too subtle (e.g., very high-quality generations) but semantic logic errors (e.g., six fingers) are present, creating a holistic detector.</li></ul><h3>3.4 Differential Learning Rates</h3><p>We applied different “learning speeds” to different parts of the model. The pre-trained backbones were updated very slowly to preserve their existing knowledge, while the new classification head was trained quickly. This allowed the model to adapt to the specific task of detecting deepfakes without forgetting the visual patterns it had already learned.</p><h3>3.5 Test Time Augmentation (TTA)</h3><p>For the final evaluation, we implemented a <strong>5-Crop Inference</strong> strategy.</p><ul><li><strong>Method:</strong> For every test image, we extract 5 crops (Top-Left, Top-Right, Bottom-Left, Bottom-Right, Center) and average their probabilities.</li><li><strong>Reasoning:</strong> AI artifacts are often inconsistent; the center of an image might appear realistic while the corners reveal generation seams.</li></ul><h3>4. Conclusion</h3><p>The transition from large, general-purpose models (ConvNeXt/DaViT) to a specialized Multi-Stream ResNet18 architecture directly addresses the problem of generalization. By explicitly modeling <strong>noise residuals</strong> and <strong>frequency spectra</strong>, and by strictly preserving pixel resolution, the system is robust against semantic overfitting and better equipped to detect unseen generative models.</p><blockquote>AI-generated images are becoming very realistic. We need new ways to check what is real and what is not. Detecting deepfakes is important because it helps us keep trust in the images we see every day.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0d901f3c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs in Practice: How I Choose the Right Model]]></title>
            <link>https://medium.com/@pamudu1111/llms-in-practice-how-i-choose-the-right-model-f87a49f2b861?source=rss-8693d059d7ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87a49f2b861</guid>
            <category><![CDATA[ai-model-selection]]></category>
            <category><![CDATA[generative-ai-software]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Pamudu]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 13:49:03 GMT</pubDate>
            <atom:updated>2025-07-29T10:57:24.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbq1EqBlrMGfeIOLXuDy6w.png" /></figure><p>This is something I’m writing based on my experience, thinking it might help you figure out which LLM model is best suited for your needs.</p><p>In this new agentic and AI era, there are a lot of LLM models out there:</p><ul><li><strong>Google</strong> — Gemini family of models</li><li><strong>OpenAI</strong> — GPT series and the O series</li><li><strong>Anthropic</strong> — Claude models</li><li><strong>xAI </strong>— Grok models</li><li><strong>Meta </strong>— LLaMA models</li><li><strong>Cohere </strong>— Command R models</li></ul><p>Many companies are now building their own models, and the number of LLMs is huge.<strong> So it’s important to have a general idea of which model to use for different tasks</strong> — whether it’s general use cases, coding, content generation, customer support automation, data analysis, research assistance, or personal productivity tools like task management and scheduling.</p><p>The use case for each individual is different. A developer, a manager, a product owner, a QA engineer — they all use LLMs in different ways.</p><p>For me, I mostly use LLMs for coding tasks. Specifically, as an AI engineer, I use them to build AI-related tools — interacting with LLMs, creating agentic workflows, managing cloud infrastructure, and building microservices. I also use them for debugging, API documentation generation, unit test creation, automating backend logic..etc.</p><p>A full-stack developer, on the other hand, might use LLMs for different types of tasks — like frontend development, backend service creation and working with databases. So even within the same job role, the day-to-day tasks and how LLMs are used can be very different.</p><blockquote>So, while the models themselves are powerful, <strong>how you use them should depend on the specific task at hand</strong>. Choosing the right approach — and the right model — can make a big difference in the quality, speed, and usefulness of the results.</blockquote><h3><strong>Common Issues I’ve Seen</strong></h3><p>I’ve often seen people test different LLMs by giving them the same prompt, comparing the outputs, and choosing whichever looks best. That’s a valid approach — I do it myself sometimes. But with a bit of understanding about how each model works, you can <strong>make smarter choices upfront and get better results more efficiently</strong>.</p><p>Another thing I’ve noticed: people often get <strong>PRO</strong> or <strong>PREMIUM</strong> subscriptions and then don’t really get the full benefit.<br><strong>For example:<br></strong> People pay for the $20 ChatGPT plan but only use the default GPT-4o model for every task. They don’t switch models. Same story with Google AI Studio or Vertex AI Studio — they stick to the default model and default settings, without even exploring other parameters.</p><p>One more point — though I won’t go too deep into it: Platforms like ChatGPT, Claude and Gemini also offer advanced tools like <strong>Canvas</strong>, <strong>Deep Research</strong>, <strong>custom GPTs</strong>, and <strong>Gems</strong> in Gemini. These tools can really help make your life easier, and they’re worth trying.</p><h3><strong>Thinking Models vs Non-Thinking Models</strong></h3><p>Now, I’ll categorise the available models into two types:</p><ul><li><strong>Thinking models</strong></li><li><strong>Non-thinking models</strong></li></ul><p><strong>Thinking models:</strong> O3, O4-mini, Gemini 2.5 Pro, ..<br> <strong>Non-thinking models:</strong> GPT-4o, Gemini 2.0 Flash, Grok 3, ..</p><p>Non-thinking models generate responses more directly and quickly, without engaging in deeper reasoning.</p><p>Thinking models, as the name suggests, “think” before giving an answer. You might already guess — because they do some reasoning internally, they tend to produce more accurate results. And yes, benchmark results usually confirm this.</p><p>So you might think: <em>“Let’s just use thinking models for everything, since they’re better.”</em><br> That’s a fair thought.<br> But — there are some catches.</p><h4><strong>Where to use Thinking and Non-thinking models</strong></h4><p>For general tasks like writing emails, summarising text, or translating content — basic, everyday tasks — non-thinking models are more than sufficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1cxb0wISC4BwNqHbHXOGA.png" /></figure><p>You really don’t need to use a thinking model for that. It’s like using a sword to cut a piece of cake. It’ll still work, but it’s overkill.</p><p><strong>When tasks get more complex — when there’s more data to analyse or more detailed instructions — it’s better to switch to a thinking model.</strong></p><p>But you have to use thinking models wisely. Take ChatGPT’s $20 plan for example. The most advanced model available there is the O3 model. It’s a thinking model, and it has <strong>rate limits</strong>. So if you use it for every little thing, you might hit the limit and be blocked from using it for a while.</p><p>Also,<strong> thinking models generally take more time to generate responses compared to non-thinking models.</strong> That might not be a big issue for most general users, but it’s something to be aware of.</p><p>Another point (without going deep into technical details): Thinking models are instruction fine-tuned to perform <strong>complex</strong> tasks, not general-purpose ones. Meanwhile, models like GPT-4o (a non-thinking model) are trained specifically for general, everyday tasks. In those tasks, the non-thinking model can even perform better.</p><p>So the key takeaway is: <strong>select the model wisely</strong>.<br> If you experiment with them for just a day or two, you’ll start getting a feel for which model suits which kind of task.</p><h3>Model Selection: Why It Makes a Difference</h3><p>If we consider a recent family of models — like Gemini 2.5 Pro, Gemini 2.5 Flash, and Gemini 2.5 Flash Lite — it’s easy to understand their relative strengths.</p><p>The Pro model is the most accurate. Flash and Flash Lite are smaller, faster variants with lower accuracy. So naturally, you might wonder: <em>“If Pro is the best, why do the others even exist?”</em></p><p>If you’re using these models through a UI (like Gemini or Vertex AI), you might not see the real reasons for having multiple variants. But when you dig deeper, the answer becomes clear: there’s a trade-off between accuracy, speed, and cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qybs9gXP64TzL6w9.png" /></figure><p>From Pro to Flash Lite, the accuracy drops, but generation speed increases. For example, Gemini 2.5 Flash Lite is lightning-fast but comes with slightly less accuracy. That can be totally fine depending on the task.</p><h4><strong>Why This Trade-off Matters</strong></h4><p>If latency isn’t an issue, you can always go for the Gemini 2.5 Pro model. But there’s a catch — cost. When using these models via API (on a pay-as-you-go basis), the Pro model is significantly more expensive than Flash Lite.</p><p>So if you use the Pro model for every small task, yes, it works — but you’ll end up paying more and increasing latency unnecessarily.</p><p>That’s why, when building production systems or pipelines, it’s essential to choose the right model based on the use case. It’s not just about getting the best answer — it’s about managing latency, cost, and accuracy together.</p><h4><strong>[Example] Real-World Coding Use Cases — GPT-4.1 Series</strong></h4><p>This is a use case where Non-Thinking models can shine.</p><p>In 2025 April, OpenAI released the GPT-4.1 series, specifically aimed at coding.<br>Variants include:</p><ul><li>GPT-4.1</li><li>GPT-4.1 Mini</li><li>GPT-4.1 Nano</li></ul><p>Just like before, the full GPT-4.1 offers the highest accuracy. Mini is a middle-ground option, and Nano is the fastest and lightest model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*0JtKS6BodsOO5jIr6I2rqQ.png" /></figure><p><em>Why did OpenAI release multiple versions? </em><strong><em>Simple — use case optimisation.</em></strong></p><p>For example:</p><ul><li>Tools like <strong>Copilot</strong>, <strong>Cursor</strong>, and other coding assistants rely on <strong>quick code suggestions and completions</strong>, where <strong>speed is more important than perfect accuracy</strong>.<br>In these cases, even if a suggestion isn’t perfect, you can easily spot and fix it yourself — so models like <strong>GPT-4.1 Nano</strong> are ideal.</li><li>For tasks like <strong>inline editing</strong> or <strong>chat-based coding</strong>, where a bit more thoughtfulness is useful and response time isn’t as critical, <strong>GPT-4.1 Mini</strong> or <strong>GPT-4.1 </strong>are better suited.</li></ul><h4>[Example] Agent Coding (or Vibe Coding)</h4><p><em>In workflows that require continuous, fast code edits (like agent coding or vibe coding), </em><strong><em>people usually don’t use thinking models. Why?</em></strong></p><p>Because thinking models take time — and these tasks involve many small, quick changes. In those cases, it’s much more practical to use non-thinking models. That’s how you keep the workflow smooth and responsive.</p><h4>[Example] ChatGPT Agent (Recent Addition)</h4><p>One interesting example I recently saw is OpenAI’s new live agent system. I don’t know the exact implementation details, but I suspect it involves model switching.</p><p>Why? Because the agent interacts live and needs to:</p><ul><li>React quickly</li><li>Handle tool use and decisions</li><li>Support multimodal input like images</li></ul><p>This kind of intelligent, responsive system likely uses <strong>multiple models</strong> — a <strong>smaller, faster model</strong> for handling simple and familiar decisions quickly, like logging into Gmail or performing routine actions, and a <strong>more capable, intelligent model</strong> when deeper analysis is needed — for example, when dealing with web pages that have many options or large amounts of content to process before taking the next step.</p><h3>LLMs at Work: Use Cases Across Job Roles</h3><p>We’ve discussed some general model use cases. Now let’s see how models are used in different scenarios.</p><h4><strong>Software Developer</strong></h4><p>Many developers are now using Claude models for coding tasks. In tools like Copilot and Cursor, both Claude and GPT-4.1 models are popular choices.</p><p>Claude models come in different versions, and the choice often depends on personal preference. Generally, <strong>newer versions offer better performance</strong> — for example, <strong>Claude 4 Sonnet</strong> typically performs better than <strong>Claude 3.5 Sonnet</strong>.</p><p>Some developers prefer using <strong>thinking models</strong> even for small code edits to ensure higher-quality suggestions, while others prioritise <strong>speed</strong> and go with faster, lighter models.</p><p>In my case — I don’t use Cursor much. I mainly use Copilot. For me, Claude 4 Sonnet usually gives a good balance of accuracy and speed. If I feel a particular edit needs more intelligence, I sometimes switch to o4-mini.</p><p>Sometimes, I’ve felt that Claude 4 over-edits my code. So in those situations, I switch to GPT-4.1. Everyone has a different way of choosing models — it’s very personal.</p><h4><strong>AI Engineer</strong></h4><p>Since I also work in this field, I’ll share some insights on how different LLMs are used for different tasks.</p><p>When developing AI tools, choosing the right model is very important.</p><p>You need to consider:</p><ul><li>Cost</li><li>Task complexity</li><li>Latency expectations from stakeholders</li></ul><p>Depending on those, you decide what kind of system to build: a RAG system, an agentic framework, or something else. I won’t go deep into architecture here, but your model choice must match your goals.</p><p>Even if a model gives perfect results, if it takes too long or costs too much, it may not be suitable.</p><p>In an AI system, it’s important to test, benchmark, and choose the right model for the task at hand — especially with new model releases coming out so frequently.</p><p>Let’s take a few simple cases:</p><ul><li>For classification tasks like<strong> intent detection </strong>or s<strong>entiment analysis</strong>, the task isn’t too complex. So you can use smaller non-thinking models like GPT-4.1 Nano or Gemini 2.0 Flash Lite to achieve fast performance without sacrificing accuracy.</li><li>For <strong>form-filling</strong> or <strong>template-based automation</strong>, such as extracting details from resumes or survey forms, smaller models work well because the task is not very complex, and these models are typically trained on a large number of similar documents — making them more familiar with such formats.</li></ul><p>⚠️<strong> A Note on Knowledge Cutoff and Libraries</strong></p><p>If you work in the software domain — especially in AI — or even in other fast-moving fields, things change rapidly. Documentation and libraries evolve quickly. So, if you ask an LLM trained on data up to 2023 about a library released in 2024, it simply won’t know the answer — no matter how well you frame the question.</p><p>I personally use Gemini 2.5 Pro for AI-related coding tasks.<strong> Even with internet access enabled to fetch relevant documentation, I’ve noticed that models often still prioritise the information they learned during training.</strong></p><p>Another very important point to consider as AI Developer — especially when working on <strong>agentic workflows or MCP (Model Context Protocol) tasks — is model selection</strong>. Choosing the right model becomes critical when you’re building agents that need to interact with tools.</p><p>In these cases, there’s a key metric called <a href="https://python.langchain.com/docs/concepts/tool_calling/"><strong>tool call</strong></a><strong> accuracy</strong> — which measures how well the LLM can identify and trigger the correct tool with correct parameters based on the situation.</p><p>From what I’ve observed, Anthropic models generally perform better in this area, with OpenAI models also working well. However, Gemini models seem to lag behind slightly in tool usage accuracy.</p><p>So, when working with agentic systems or MCP-style tool calls, it’s important to select a model based on a careful balance of tool call accuracy, latency, and cost.</p><blockquote><strong>As LLMs continue to evolve, the number of models — and the ways to use them — will only grow. What really matters isn’t just knowing <em>what models exist</em>, but understanding <em>how to choose the right one for the task</em>. Whether you’re a developer, AI engineer, product manager, or researcher, your needs will differ — and so should your approach.</strong></blockquote><blockquote><strong>Take time to explore, experiment, and observe how different models perform in your workflows. A little awareness can go a long way in improving both productivity and cost-efficiency.</strong></blockquote><blockquote><strong>In the end, it’s not about finding the “best” model — it’s about finding the right model for the moment.</strong></blockquote><p><strong>Pamudu Ranasinghe</strong><br><a href="https://scholar.google.com/citations?user=v1CeOs0AAAAJ&amp;hl=en">Google Scholar</a> | <a href="https://www.linkedin.com/in/pamudu-ranasinghe/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f87a49f2b861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Election Vote Counting]]></title>
            <link>https://medium.com/@pamudu1111/automated-election-vote-counting-7b89900f7333?source=rss-8693d059d7ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b89900f7333</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[vote-counting]]></category>
            <dc:creator><![CDATA[Pamudu]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 20:04:48 GMT</pubDate>
            <atom:updated>2024-09-27T21:09:49.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>On the 21st of September, we had our presidential election. While watching the manual process of counting votes, I started thinking about ways to automate it. One quick note — the most efficient solution would be to introduce an electronic voting system instead of the traditional pen-and-paper method. For example, we could use an electronic voting system with fingerprint verification to ensure unique votes.</p><p>However, today I won’t focus on these methods. Right now, Sri Lanka, like many other countries, still uses the pen-and-paper voting method. So, I want to suggest some ways to<strong> automate the vote-counting process</strong>.</p><p>On the election day, I coded four methods for doing this.</p><h4>Data Creation</h4><p>For this experiment, I created sample ballot sheets using Photoshop with some random names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_ApdZb6Jn2BGn9XT2m4c5Q.png" /></figure><h3>1. Using ChatGPT Vision API to Process Ballot Papers</h3><p>The <strong>ChatGPT Vision API</strong> offers a simple and effective method for processing ballot papers, using the intelligence of Large Language Models (LLMs). This reduces the need for complex custom algorithms to process the ballot paper.</p><p>I chose the <strong>GPT-4o-mini</strong> model, balancing cost and accuracy for our needs.</p><p>This approach efficiently handles many complexities thanks to the model’s advanced capabilities. The process only requires two key elements:</p><ol><li>A well-crafted prompt with clear instructions</li><li>A defined output schema</li></ol><p>By providing these, the API can analyze images of ballot papers, interpret the votes, and return structured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*MKCf6lWMEXulcvGmXsZ9ig.png" /></figure><p>The <strong>prompt</strong> that I used for processing</p><pre>Analyze the provided ballot paper image to determine the validity of the vote and extract the preference order. The output should be a structured JSON object containing the following details:<br><br>[Steps]<br>1. Image Analysis:<br>    - Scan the ballot paper for the presence of numbers (1, 2, 3) or a cross sign (X) next to candidates&#39; names.<br>2. Determine Validity:<br>    - Valid Ballot: <br>        - Contains only a cross sign (X) without any numbers.<br>        - Contains numbers (1, 2, 3) without a cross sign.<br>    - Invalid Ballot:<br>        - Contains both a cross sign (X) and numbers (1, 2, 3).<br>        - Contains incorrect or duplicated numbering, or is missing required numbers.<br>3. Extract Vote Preferences:<br>    - If the ballot is valid, extract the candidate names and their positions on the ballot sheet corresponding to the votes.<br>    - If the cross sign is present, treat the candidate marked with the cross as the first preference.<br>    - Ensure no other markings or errors are present that would invalidate the ballot.<br>4. Output the Following JSON Structure:<br>{<br>&quot;validity&quot;: true or false,<br>&quot;explanation_for_validity&quot;: &quot;Explanation for why the ballot is valid or invalid.&quot;,<br>&quot;cross_or_numbering&quot;: true or false,<br>&quot;votes&quot;: {<br>    &quot;1st_vote&quot;: {<br>        &quot;name&quot;: &quot;Candidate Name&quot;,<br>        &quot;position_on_ballot_sheet&quot;: &quot;Position Number&quot;<br>    },<br>    &quot;2nd_vote&quot;: {<br>        &quot;name&quot;: &quot;Candidate Name&quot;,<br>        &quot;position_on_ballot_sheet&quot;: &quot;Position Number&quot;<br>    },<br>    &quot;3rd_vote&quot;: {<br>        &quot;name&quot;: &quot;Candidate Name&quot;,<br>        &quot;position_on_ballot_sheet&quot;: &quot;Position Number&quot;<br>    }<br>}<br>}<br><br>[Example Cases]<br>    1. Valid Ballot with Cross Only:<br>    - Image Analysis: Detect a cross sign next to a candidate.<br>    - Validity: True<br>    - Explanation: &quot;The ballot is valid with only a cross sign present, no numbers.&quot;<br>    - Cross or Numbering: True<br>    - Votes: <br>        - 1st Vote: {&quot;name&quot;: &quot;Mahesha Hettiarachchi&quot;, &quot;position_on_ballot_sheet&quot;: &quot;6&quot;}<br>2. Valid Ballot with Numbering Only:<br>    - Image Analysis: Detect numbers 1, 2, 3 next to candidates.<br>    - Validity: True<br>    - Explanation: &quot;The ballot is valid with numbers 1, 2, 3 clearly marked.&quot;<br>    - Cross or Numbering: False<br>    - Votes: <br>        - 1st Vote: {&quot;name&quot;: &quot;Tharindu Fernando&quot;, &quot;position_on_ballot_sheet&quot;: &quot;3&quot;}<br>        - 2nd Vote: {&quot;name&quot;: &quot;Shenal Rathnayake&quot;, &quot;position_on_ballot_sheet&quot;: &quot;4&quot;}<br>        - 3rd Vote: {&quot;name&quot;: &quot;Mahesha Hettiarachchi&quot;, &quot;position_on_ballot_sheet&quot;: &quot;6&quot;}<br>3. Invalid Ballot with Cross and Numbering Both Present:<br>    - Image Analysis: Detect both cross sign and numbers.<br>    - Validity: False<br>    - Explanation: &quot;The ballot is invalid because it contains both a cross sign and numbers.&quot;<br>    - Cross or Numbering: False<br>    - Votes: {}</pre><h3>2. Process the Layout with OCR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*SxRD1eyykfr2GPLOFBDh-Q.png" /></figure><p>In this method, I’ve used a layout extraction technique followed by a rule-based approach to process and extract the details from the structured OCR text.</p><p>Simply using OCR engines that output only text won’t work here because we need structural information as well. For this, I’ve used the <strong>LLMWhisperer API</strong>, which provides structured OCR output.</p><p><a href="https://llmwhisperer.unstract.com/"><strong>2.1 LLMWhisperer API</strong></a></p><p>- Offers high-quality output with structured text.</p><p>- It’s free for up to 100 sheets per day, which is sufficient for this implementation.</p><p>We can achieve similar results using on-device OCR engines like Tesseract by obtaining the word locations along with the text, but it requires some additional processing, LLMWhisper API provides a better and more organized output, especially when handling unknown symbols, cross marks (X) and hand-written digits (1,2,3).</p><p><strong>Example Output from LLM Whisper</strong></p><pre>Pamudu Ranasinghe<br>Kasun Jayawardena     [X]<br>Tharindu Fernando     [X]       3<br>Shenal Rathnayake     [X]       1<br>Mahesha Hettiarachchi [X]       2</pre><p>Symbols that are not recognized as letters or numbers are output as [X].</p><p>I used a manual, rule-based method to extract and validate the vote.</p><p><strong>2.2 Text Processing:</strong></p><ul><li>Simple text processing allows us to extract the votes and candidates.</li><li>Additional logic is needed to handle cases where extracted markers (X, 1, 2, 3) are not on the same line.</li></ul><p><strong>2.3 Vote Validation</strong></p><pre>- The ballot cannot be empty.<br>- Valid votes can only be marked with &#39;X&#39;, or numbers (&#39;1&#39;, &#39;2&#39;, &#39;3&#39;).<br>- If &#39;X&#39; is marked, No other votes should be present like numbers of any other &#39;X&#39; marks<br>- If using numbers, &#39;1&#39;, &#39;2&#39;, and &#39;3&#39; , there should not be any other symobles (&#39;X&#39;)<br>If these rules are followed, the ballot is considered valid.</pre><p><strong><em>Note</em></strong></p><p>This rule-based method is simple but requires handling edge cases, like when marks and votes are misplaced or misaligned.</p><p>Though this method isn’t as intelligent as an LLM-based method, it is more robust in terms of cost-efficiency, especially when handling a large number of inputs.</p><p>Now I will discuss how LLMs can be used to process structured text instead of a rule-based method.</p><p><strong>2.3 Structured Output + LLM</strong></p><p>We can use the intelligence of Large Language Models (LLMs) to process structured output from the ballot paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*qdrgMk7WxPTwRlTX1W-luQ.png" /></figure><p><strong>Reduce the Cost:</strong> By processing only structured text, we can keep the token usage low (compared to vision API). This contrasts with the earlier method using the LLM vision API, <strong>where analyzing the entire image led to high input tokens and associated costs.</strong> We can use a lower-cost model for this task because it is simpler, further reducing expenses.</p><h3><strong>3. Using Object Detection — YOLO</strong></h3><p>For this implementation, I’m using <a href="https://docs.ultralytics.com/"><strong>YOLOv8</strong></a>. YOLOv8 is well-maintained by the Ultralytics team and is very user-friendly. With just a few lines of code, I can train a model, making it super easy to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*UnxnZA7vDmWCbzhymxvaEA.png" /></figure><p>For image annotation, I used the <a href="https://roboflow.com/"><strong>Roboflow</strong></a> platform. It’s my go-to choice for annotating images due to its intuitive interface and efficient workflow.</p><p>To increase the dataset size and improve model generalizability, I applied several <strong>augmentations</strong> like Random crop, Rotation and Brightness adjustments. I also used some <strong>bounding box-level augmentations</strong> (bounding-box level rotation, blur, brightness, etc) as well.</p><p>Using this augmented dataset, I trained a <strong>YOLOv8 nano</strong> model. I chose the nano variant because I didn’t annotate many images. With a small number of annotated images, the nano variant is a good fit due to its smaller size and faster training time.</p><p>It’s important to note that for a production-level implementation, YOLOv8 nano might not be the best choice. We would need to consider licensing issues and require a larger, more diverse annotated dataset. However, I won’t delve deeper into that topic here.</p><p><strong>Post-processing</strong><br>After object detection, manual post-processing is needed to extract the votes corresponding to each candidate’s position. Since we’re not using an OCR (Optical Character Recognition) method, we can’t extract the candidate names, but that’s not necessary for our purpose.</p><p>The output we get from this method is a dictionary in the following format:</p><p><em>{candidate position on the ballot: vote}</em></p><pre>[Example 1]<br>  {1: None, <br>  2: &#39;cross&#39;, <br>  3: None, <br>  4:None}<br><br>[Example 2]<br>  {1: 3, <br>  2: &#39;cross&#39;, <br>  3: None, <br>  4:1}</pre><p>From this, if needed, we can manually map the position on the ballot to the candidate’s name.</p><p>The next step is to validate whether this is valid vote or not.</p><p>[2.3] The same rules are checked here as well for validation.</p><h3>4. Vote Extraction Using Computer Vision</h3><p>Here’s a step-by-step breakdown of the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*wc4WB2dCXu9-wqWb1UIOjQ.png" /></figure><p><strong>4.1 Initially, basic computer vision techniques are applied to preprocess the image.</strong></p><ul><li>The image is resized to 480x640 pixels and then processed as follows:</li><li>Converted to grayscale.</li><li>Blurred to reduce noise.</li><li>Edges are detected using the Canny edge detector.</li><li>The edges are then dilated and eroded to close gaps and highlight important features.</li></ul><p><strong>4.2 Finding the Biggest Contour:</strong></p><p>identifies the largest contour in the image based on the area.</p><ul><li>This contour represents the boundary of the ballot paper.</li><li>The perspective of this contour is then warped (corrected) to align it properly for further processing.</li></ul><p><strong>4.3 Identifying Horizontal Lines that Separate Candidate Names:</strong></p><ul><li>A horizontal kernel is created to detect horizontal structures, like the lines separating candidate names.</li><li>Contours (outlines) of these horizontal lines are then detected in the processed image.</li><li>Only lines that meet a minimum width threshold are kept, filtering out shorter, irrelevant lines.</li><li>The coordinates of the detected horizontal lines are extracted for further use.</li></ul><p><strong>4.4 Extracting Candidate Regions:</strong></p><ul><li>Using the identified horizontal lines, the regions corresponding to each candidate’s section on the ballot paper are extracted.</li><li>From these regions, symbols like vote marks (crosses, numbers like 1, 2, 3) are identified using <strong>template matching</strong>.</li></ul><p><strong>4.5 Template Matching for Vote Symbols:</strong></p><ul><li>The candidate regions are processed to detect specific vote symbols using the following steps:</li><li>The region is converted to grayscale.</li><li>Then, template matching is performed within the extracted candidate region to identify any vote symbols that are present</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4v9E29oPyggWRTm55dQaw.png" /><figcaption>Outputs after different processing steps</figcaption></figure><p><strong>*<em>Template matching</em></strong> is performed by sliding the template over the region and calculating a similarity score at each position using a method like cv2.TM_CCOEFF_NORMED.</p><p>The position with the highest similarity score is considered the best match. If the score exceeds a threshold, the symbol is considered valid.</p><p>The results (symbol, its position, and similarity score) are returned. If no symbol exceeds the threshold, it is classified as “Unknown.”</p><p>This method doesn’t use OCR (Optical Character Recognition), so candidate names can’t be extracted directly similar to the previous object detection method. Instead, it uses the candidate’s position on the ballot. If needed, we can manually map ballot positions to candidate names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*KR3KI5vsVMrySyl81Vwc1A.png" /><figcaption>Template matching output</figcaption></figure><p><strong>Note on CV method:</strong></p><p>This method assumes a specific ballot layout with horizontal lines separating candidates. It may need adjustments for different ballot designs.</p><p><strong>Limitations</strong></p><ol><li>Orientation sensitivity: The system may fail if the ballot is upside down or severely rotated.</li><li>Template dependency: Accuracy depends on how well the pre-defined templates match the actual symbols on the ballot.</li><li>Lighting and image quality: Poor lighting or low-quality images may affect the accuracy of symbol detection.</li><li>Scale sensitivity: If the ballot size varies significantly from the expected size, it may affect symbol detection accuracy.</li></ol><p>Find the code: <a href="https://github.com/pamudu123/vote-counter">https://github.com/pamudu123/vote-counter</a></p><p>If you have any queries, please reach out to me. Your feedback and new ideas are greatly appreciated.</p><p><em>Pamudu Ranasinghe</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b89900f7333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guess The Country]]></title>
            <link>https://medium.com/@pamudu1111/guess-the-country-4b983ff36616?source=rss-8693d059d7ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b983ff36616</guid>
            <dc:creator><![CDATA[Pamudu]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 09:55:40 GMT</pubDate>
            <atom:updated>2024-01-01T12:37:35.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The inception of the “Guess The Country” game was inspired by the compelling <a href="https://www.youtube.com/watch?v=UIZAiXYceBI&amp;ab_channel=Google">demo</a> presented by Google to showcase their groundbreaking model, “Gemini .” Witnessing the capabilities of the Gemini models and their potential to craft an immersive gaming experience left me truly amazed. The game concept that emerged from this demonstration offers users a dynamic platform enriched with remarkable audio and interactive features.</p><p>I particularly appreciated the performance of the Google Gemini Ultra, as highlighted in my <a href="https://www.linkedin.com/pulse/my-thoughts-new-google-gemini-pamudu-ranasinghe-jhc7c%3FtrackingId=bWrbx9C8SLSn%252BA1iw6RPdQ%253D%253D/?trackingId=bWrbx9C8SLSn%2BA1iw6RPdQ%3D%3D">previous LinkedIn post</a>. The model seamlessly integrates text, video, and audio functionalities, and the “Guess the Country” game, featured in the Google demo, exemplifies Gemini’s prowess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRk3Ql8ttEIIB5DGEmqQMQ.png" /><figcaption>Figure 1: The ‘Guess the Country’ features on the “Google Gemini Ultra” Demonstration video.</figcaption></figure><p>In the Google Demo game, the game provides an explanation of a country using emojis, enhancing the user experience with accompanying audio descriptions. The challenge for users is to guess the country based on these hints. Users actively engage with the machine, expressing reactions such as “that’s easy,” fostering a highly interactive gaming environment.</p><p>I replicate this game for play in our local setting. Although we lack access to the powerful audio, video, and text multimodal capabilities of Google Gemini, currently exclusive to Google, we construct a dedicated game environment for the “Guess the Country” game.</p><p>Here is our version of the game. The initial step involves setting up the world map, positioned to the camera. Basic instructions are displayed within the game, and players are tasked with guessing the country within a specified time frame based on the displayed emojis. To aid those facing challenges, a hint feature has been introduced. Hints offer descriptive information about the emojis, assisting players in making more informed guesses. As the game unfolds, users continue guessing, striving to identify countries within the given time frame. This dynamic and engaging gameplay ensures a captivating experience for players.</p><h3>Methodology</h3><p>Now, let’s discuss how this game is created step by step.</p><h4><strong>STEP 1</strong></h4><p>First, we need to get a good map. I had a hard time identifying a suitable map for this game, as I tried several maps bought from the stationary shop. Most of the maps are blue, making it a bit difficult to differentiate between the sea and countries. Therefore, a map with the country boundaries in black and white is better, and that’s the type of map I am using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*J_Si4ClbvipwDPK6wmMGYQ.png" /><figcaption>Figure 2: A good map for our game; the boundaries of the countries are clearly visible.</figcaption></figure><h4>STEP 2</h4><p>The next step is to find a way to identify the country locations with the corresponding country names. For that, I am using an image segmentation model — specifically, the YOLOv8 segmentation model.</p><p><strong>Why YOLOv8?</strong></p><p>The reasons behind choosing YOLOv8 are that YOLO models provide excellent real-time speed, and with the pre-trained ImageNet weights, it can be trained with a relatively lesser number of annotated images. Another reason is that YOLOv8 is very easy to use; Ultralytics has packaged it, and with just 3 to 4 lines of code, we can train the model. Additionally, we can conveniently train the model on Google Colab.</p><p><strong>Computer Vision Algorithms Fail…</strong></p><p>I think it is worth mentioning that, initially I considered using traditional computer vision algorithms to separate countries. However, due to various lighting conditions, especially when placing the camera on top of the map, which introduces shadows, I decided to use an intelligent algorithm to segment out countries.</p><h4>2.1 Camera Setup</h4><p>I used my phone’s camera with a mobile app called ‘<a href="https://play.google.com/store/apps/details?id=com.pas.webcam&amp;hl=en&amp;gl=US">IP Webcam</a>.’ To make it work, both my phone and computer had to be on the same WiFi. I kept the phone steady using a phone holder for the right height. If you have a webcam with adjustable height, it makes things easier.</p><h4><strong>2.2 Image Annotation</strong></h4><p>First, I set up the camera and captured video recordings, which I later converted into frames. To reduce redundancy, I have skipped adjacent frames and saved frames with a skipping frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*4DZGqQH_bt9nnUSgZIxHKA.png" /><figcaption>Figure 3: Extract frames from the video</figcaption></figure><p>Next, I compiled an image dataset and uploaded it to the <strong>Roboflow</strong> annotation platform. While other annotation platforms or local tools like <strong>LabelMe</strong> could be used, I chose to annotate images with bounding boxes. For this, I focused on <strong>eight countries</strong>: the <strong>United States of America, Australia, Greenland, Brazil, Canada</strong>,<strong> India, Russia,</strong> and <strong>China</strong>. These larger countries made annotation easier.</p><p>The annotated images were augmented by variations in random brightness, exposure, contrast, and zoom. This augmentation was selected to simulate potential real-time scenarios where such variations might occur.</p><p>Manual image segmentation is a time-consuming task. Instead of segmenting the countries directly, I drew bounding boxes around them. These bounding boxes didn’t need to match exactly; an approximate fit was sufficient.</p><p>After that, the annotations were downloaded in PASCAL VOC format XML files from the Roboflow platform instead of the YOLO format, as the PASCAL format is easy for our later processing.</p><p>I’ve generated segmentation masks using <strong>Meta AI’s </strong><a href="https://segment-anything.com/"><strong>Segment Anything</strong></a><strong> model (SAM)</strong>. I provided bounding boxes as prompts to the SAM model and the model produced corresponding masks for those bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*YCjMSZvWha2VpJcqGALDIg.png" /><figcaption>Figure 4: The workflow for image annotation: starting with bounding box annotation using Roboflow exporting these annotations in Pascal VOC format, then feeding them into the Segment Anything Model (SAM) to obtain segmented masks.</figcaption></figure><p><a href="https://github.com/pamudu123/guess-the-country/blob/main/Segmentation/bbox2seg.py">Code for automated annotating process</a></p><p>Following this preparatory work, we now possess a dataset with segmentation masks for the selected countries.</p><h4>STEP 3</h4><p>The subsequent step involves training the segmentation model. I chose the <strong>YOLOv8 Small</strong> model and trained it on<strong> Google Colab</strong> using a T4 GPU for 100 epochs. This way we have created a segmentation model for our game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*KRkNDWVcoOrnVGgofV1OYw.png" /><figcaption>Figure 5: Trained results on YOLOv8 segmentation model.</figcaption></figure><h4><strong>STEP 4</strong></h4><p>The next step is to prepare emojis with their descriptions for different countries. I used <strong>GPT-4V</strong> for that task and organized them in an Excel file. You can also come up with your own creative emojis and descriptions.</p><pre>Country Code: USA<br>Country Name: United States of America<br>Emojis: 🗽 🦅 🍔 🌽<br>Description: Symbolized by the Statue of Liberty, representing freedom and democracy. The bald eagle signifies strength and freedom. Hamburgers are iconic in cuisine, and corn is a staple crop.<br><br>Country Code: AUS<br>Country Name: Australia<br>Emojis: 🦘 🐨 🏄‍♂️ 🌊<br>Description: Known for unique wildlife, including kangaroos and koalas. Famous for surfing spots and beautiful ocean waves. The landscapes range from beaches to deserts.<br><br>Country Code: GREENLAND<br>Country Name: Greenland<br>Emojis: 🧊 🐋 🎣 ❄️<br>Description: Characterized by vast ice sheets and a cold climate. Whaling and fishing are traditional activities. The environment is harsh but beautiful, with pristine snow and ice landscapes.<br><br>Country Code: BRAZIL<br>Country Name: Brazil<br>Emojis: ⚽ 🌳 🎭 ☕<br>Description: Celebrated for its love of soccer and the lush Amazon Rainforest. Vibrant Carnival festival showcases rich cultural heritage. Renowned for coffee production.<br><br>Country Code: CANADA<br>Country Name: Canada<br>Emojis: 🍁 🏒 🐻 ❄️<br>Description: Famous for natural beauty, including maple trees and autumn leaves. Ice hockey is a beloved sport. Known for diverse wildlife and cold winters.<br><br>Country Code: INDIA<br>Country Name: India<br>Emojis: 🕌 🌶️ 🐅 🧘‍♂️<br>Description: A land of diverse cultures and history, symbolized by the majestic Taj Mahal. Spicy cuisine and vibrant festivals reflect the rich heritage. Tigers roam national parks, and yoga has its origins here.<br><br>Country Code: RUSSIA<br>Country Name: Russia<br>Emojis: 🏰 🐻 🚀 ❄️<br>Description: Known for rich history and cultural landmarks like the Kremlin. Vast landscapes are home to bears and a cold climate. Significant contributions to space exploration.<br><br>Country Code: CHINA<br>Country Name: China<br>Emojis: 🐲 🍚 🏮 👲<br>Description: History is symbolized by the dragon, a sign of power and good luck. Cuisine, including rice, is a staple. Traditional festivals and attire reflect a rich cultural tapestry.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyPMbtE3lYSJofLTimGBCQ.png" /><figcaption>Figure 6: Created Excel file with country emojis and descriptions</figcaption></figure><p>Excel file <a href="https://github.com/pamudu123/guess-the-country/blob/main/GUI/resource_files/country_descriptions.xlsx">Link</a></p><h4><strong>STEP 5</strong></h4><h4><strong>5.1 Identify hand gestures</strong></h4><p>For hand detection, I’ve chosen the <strong>MediaPipe</strong> library due to its exceptional speed and accuracy in identifying hand key points. The library consistently detects 21 hand landmarks, offering detailed information about hand poses. Unlike alternative keypoint detection algorithms such as YOLO Pose, MediaPipe has a module purposely built for hand tracking, making it a reliable choice for precise and efficient hand pose recognition.</p><h4><strong>5.2 Check which finger is up</strong></h4><pre>def is_finger_raised(tip_y, pip_y, image_height):<br>    return tip_y &lt; pip_y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*-9TZvGizlEDZI3nXF8HNLw.png" /><figcaption>Figure 7: Explanation of the logic behind identifying whether the finger is raised or not</figcaption></figure><p>If the y-coordinate of the fingertip is greater than the y-coordinate of the proximal interphalangeal joint, it implies that the finger is raised.</p><h4><strong>5.3 The Country Identification Process</strong></h4><p>To determine whether the current index finger position is within a country, I need to input the set of masks from the YOLO model and the current position of the tip of the index finger to a custom function.</p><pre>def find_mask_for_coordinate(masks, coordinate):<br>    x, y = coordinate<br><br>    for mask_index,mask in enumerate(masks):<br>        mask  =  masks[mask_index,:,:]<br>        mask_array = np.array(mask)<br><br>        # Ensure that the coordinate indices are integers<br>        x_index = int(x)<br>        y_index = int(y)<br><br>        pixel_value = mask_array[y_index, x_index]<br>        if pixel_value == 1:<br>            # Return the index of the mask if the point is inside<br>            return mask_index  <br><br>    return None</pre><p>The function checks whether the desired location pixel value is equal to 1, indicating that the coordinate is inside the current mask. If so, it returns the index of that mask. If the coordinate is not found in any mask, the function returns None. The purpose of this function is to identify which mask, if any, contains a given coordinate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*kDhlYjMe7jeetEZzSdo9DQ.png" /><figcaption>Figure 8: Segmented binary masks from the YOLO model</figcaption></figure><p>In this context, the set of masks refers to the output of the YOLO segmentation model, which provides a<strong> binary mask</strong> for each country. In my case, I have obtained 8 masks since I annotated data only for 8 countries. This function enables the identification of the specific country corresponding to a given coordinate, allowing us to determine the country the player is pointing to.</p><h4><strong>STEP 6: GUI Implementation</strong></h4><p>For the implementation of the GUI, I chose the <strong>PySide6</strong> library due to its permissive license, which is suitable for our project development. To incorporate real-time camera feed and hand position detection, a separate thread runs alongside the main thread to ensure smooth functionality.</p><h3><strong>Combining Everything</strong></h3><p>Let’s delve into the game dynamics. The initial window provides instructions, the user can start by clicking the button or pressing enter. Then transition to the subsequent window where the actual gameplay comes to life. On the left side, there’s a camera view, and players are tasked with pointing to the country represented by emojis.</p><p>Behind the scenes, the game employs MediaPipe’s hand-tracking module to detect hand points as players move their hands. Every hand position takes into account how the fingers are positioned, and different actions are associated with different finger setups. To counteract false predictions during hand movement, players must maintain their hand over a country for a specified duration for a selection.</p><p>The gameplay involves users pointing to a country using their index finger. Correct guesses contribute to the correct score, while incorrect ones increment the incorrect score.</p><p>For a hint on the displayed emojis, players reveal two raised fingers, and the corresponding guess appears on the GUI. To pause the game, players display all five raised fingers; to resume, they replicate the gesture of raising all five fingers. This interactive and gesture-driven approach adds an engaging layer to the gaming experience.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9gTek0wQywc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9gTek0wQywc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9gTek0wQywc%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/a603c87c54ac3086df96b13c634d2ac4/href">https://medium.com/media/a603c87c54ac3086df96b13c634d2ac4/href</a></iframe><h4><strong>LIMITATIONS</strong></h4><p>1) The detection and tracking method employed by Mediapipe relies on the initial detection of the entire hand. If the hand cannot be detected, tracking won’t occur, and there’s a risk of missing detection when only a part of the hand is visible.</p><p>2) Optimal results are achieved when the camera remains stationary during the gameplay. This is because the country masks are initially detected, and subsequent calculations are based on that information. If there are changes in the positions of these country masks due to camera movement, it can impact the gameplay results.</p><p>3) Clear visibility of the fingers is crucial for the system to function. If the fingers are covered for any reason, the system won’t work effectively, particularly in identifying the pointing fingers.</p><p>4) The functionality of the system relies on the YOLOv8 segmentation model. If different types of country maps are used, it may lead to failures in the segmentation and detection process.</p><p>5) The system needs to be trained with a diverse set of world maps. Annotating these maps even with the bounding boxes is a time-consuming task.</p><p>6) If the user plays the game a second time, the same country, emojis, and hints will be present.</p><h3><strong>Improvements</strong></h3><ol><li>Implement <strong>difficulty levels</strong>, such as easy (5 emojis), medium (4 emojis), and hard (3 emojis), adjusting the time given for each difficulty level.</li></ol><p>2. Introduce a <strong>Game Over scenario</strong> upon reaching 3 incorrect guesses.</p><p>3. <strong>Set up a high-score system</strong> to track and display players’ achievements.</p><p>4. Enhance the hint interaction by having the system <strong>speak the hint</strong>, increasing the overall interactivity of the game.</p><p>5.<strong> Use different sets of emojis and hints</strong> for each game to provide a fresh and varied experience with new challenges every time.</p><p>This concludes the implementation of Guess the Game. Feel free to share any suggestions, and I invite you to give it a try!</p><p><a href="https://github.com/pamudu123/guess-the-country">Github Link</a> for this project</p><p>Pamudu Ranasinghe</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b983ff36616" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>