<?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 Lalitha Raman on Medium]]></title>
        <description><![CDATA[Stories by Lalitha Raman on Medium]]></description>
        <link>https://medium.com/@lalithasandeepraman?source=rss-7b3b21471452------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hXZDairyUzMwpngi</url>
            <title>Stories by Lalitha Raman on Medium</title>
            <link>https://medium.com/@lalithasandeepraman?source=rss-7b3b21471452------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:28:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lalithasandeepraman/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[Computer Vision Digest — Issue #3]]></title>
            <link>https://ai.plainenglish.io/computer-vision-digest-issue-3-fece6987c489?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/fece6987c489</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 09:36:37 GMT</pubDate>
            <atom:updated>2026-01-02T09:36:37.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision Digest — Issue #3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*NZBxWXuGhLu3RArkAg-L5A.jpeg" /></figure><p>Welcome to the third issue of the Computer Vision Digest — a simple summary of important CV concepts and fun facts. This issue will cover:</p><p>SHAP<br>Augmentation<br>Terms to know<br>Fun Facts<br>Quiz</p><p><strong>Writer’s note:</strong><br><em>My journey into ML and specifically CV has been exciting and fun filled! Lots of interesting concepts and applications came my way. This is an attempt to share some of that with all of you. I have tried to distil the essence into an easy read so that learners without a deep background in ML can also understand the material. If your interest is piqued, references provided will allow you to dive deeper into the content. Happy Reading!</em></p><h3>SHAP</h3><p>SHAP (<strong>SH</strong>apley <strong>A</strong>dditive ex<strong>P</strong>lanations) is a popular XAI (Explainable AI) framework that explains how much each feature contributed to a model’s prediction for a specific instance.</p><p>SHAP borrowed the idea of <strong>Shapley values</strong>, from the cooperative game theory and applied it to machine learning.</p><p><strong>How SHAP works<br></strong>SHAP works by computing how the prediction changes when features are added in every possible combination, then averaging those changes in a mathematically fair way.</p><p>Say there are <strong>n</strong> features in a model. These features can be combined in <strong>2</strong> power <strong>n</strong> ways. Let there be a feature <strong>A</strong>. Now SHAP considers all combinations where feature <strong>A</strong> is absent.</p><p>Suppose a feature <strong>A</strong> is removed, SHAP computes the predictions for all the combinations without the feature <strong>A</strong>, let those subsets be <strong>S</strong>. For each such subset in <strong>S</strong>, compute how much prediction changes when <strong>A</strong> is added. This measures:<br> “How much did feature <strong>A</strong> contribute to the prediction?”</p><p>Then take a weighted average of all the above predictions. This weighted sum gives Shapley value for the feature <strong>A.</strong></p><p><strong>Why is SHAP powerful<br></strong>Consistence: If a model relies more on a feature, SHAP ensures its importance value doesn’t decrease.</p><p>Local and Global Explanations: SHAP is fundamentally a local explanation method, but because its local Shapley values are mathematically consistent (due to the weighted average over all subsets), they can be aggregated to form reliable global explanations. SHAP Force plot explains single(local) prediction. SHAP Summary plot shows global explanations.</p><p><strong>SHAP model types</strong></p><ul><li>Kernel SHAP is the model agnostic version of SHAP</li><li>Other model specific versions of SHAP are:<br>TreeSHAP for Tree models<br>DeepSHAP for Deep networks<br>Linear SHAP for Linear models</li></ul><p><strong>SHAP Example<br></strong>SHAP value = how much a feature shifts the prediction away from average, for this specific input</p><p>Consider sale of ice-creams on a specific day. Let the average sales on a day be 100 units. Now consider just one feature Rain.</p><p>On a rainy day- predicted sales = 80 units<br>On a non-rainy day- predicted sales = 120 units</p><p>SHAP value for Rainy day =80–100= <strong>-20</strong></p><p>It means that rain reduces sales by 20 compared to average.</p><p><strong>SHAP-LIME comparison</strong></p><p>Although both SHAP and LIME(For more information on LIME, read <a href="https://medium.com/@lalithasandeepraman/lime-a-simple-explanation-bfa7f92e040d">Medium article</a>) work by perturbing / omitting features, but SHAP is considered more reliable because it follows strict mathematical proven formula.</p><p>LIME does not test all contextual combinations but samples random perturbations. It is a heuristic and does not satisfy these axioms therefore:</p><ul><li>Explanations can be unstable</li><li>Explanations may contradict model behavior</li><li>Feature importance can flip between runs</li></ul><h3><strong>Concept Highlight</strong></h3><p><strong>What is Augmentation</strong></p><p>Augmentation for vision means creating a synthetic dataset by slightly modifying the input image.<em> </em>This helps the model to handle real-world images. For example, even if the image of a cat is slightly tilted or is not clear due to improper lighting, the model will still be able to identify it as “cat” because the model is trained to handle different variations of the image.</p><p><strong>Augmentation types<br></strong>Some of the augmentation types are:</p><ul><li>Rotate the original image by 10o clockwise or anticlockwise</li><li>Flip/crop the original image to create a new image</li><li>Slightly change the brightness/contrast/saturation of the original image to create a new image</li><li>Occlude/ randomly erase portions of image to create a new image</li><li>Add noise to the original image to create a new image</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*Cj8a146I8voJT2ffY2tjCg.jpeg" /><figcaption>The digit 5 is augmented in different ways</figcaption></figure><h3><strong>Terms to know:</strong></h3><p><strong>Feature Map</strong>: It is the output of a CNN layer. It is a tensor with numeric values with each channel of the tensor showing learned patterns/features of the input image.</p><p><strong>Patch Embedding</strong>: ViT splits an image into patches and converts each patch into a vector called a patch embedding.</p><p><strong>Self-Supervised Learning (SSL)</strong>: SSL is a training method where a model learns useful representations without using human-labelled data.</p><h3><strong>Fun Facts</strong></h3><ul><li>Early CV models used hand-crafted rules like “look for edges at 45 degrees.” Deep learning replaced these with automatically learned features.</li><li>Although Canny is about 40-year-old, but it is still important to understand because it’s like your teacher forcing you to learn long division even though calculators exist.</li><li>Flattening means turning a multidimensional tensor into a one-dimensional vector</li></ul><h3><strong>Quiz</strong></h3><p>1. How does an object get detected even if the image is upside down?</p><p>2. What is Sobel, Canny and Laplacian?</p><p>3. What do you mean by emergent property in the context of Deep Learning?</p><p><em>Ans1: Because the model is trained on augmented data. Even if the object is rotated or flipped upside down, it still belongs to the same class.<br>Ans2: Gradient based edge detector operators<br>Ans3: A large model develops a property even if it was not explicitly trained for it. Example: LLMs like GPT can understand grammar in a sentence like verb, tense, subject, punctuation etc. even though the model is not trained explicitly for grammar. Small models cannot do this. As the model size and data scale increase, the ability suddenly appears.</em></p><blockquote>Thanks for reading this edition. Stay tuned for the next digest with new CV concepts!<br>For questions or suggestions, message me on Medium.<br>Follow me on Medium for future digests!</blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fece6987c489" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/computer-vision-digest-issue-3-fece6987c489">Computer Vision Digest — Issue #3</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emergent Behavior of Transformers]]></title>
            <link>https://ai.plainenglish.io/emergent-behavior-of-transformers-1fded3d15394?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fded3d15394</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 19:05:56 GMT</pubDate>
            <atom:updated>2025-12-11T19:05:56.627Z</atom:updated>
            <content:encoded><![CDATA[<p>This document briefly explains the attention heads and its emergent property in transformers.</p><p><strong>Emergent behavior</strong> in Transformers, is the kind of behavior that does not exist in small models but suddenly appears as the scale increases. As a Transformer becomes larger and is trained on huge datasets surprising things happens, some are listed below.</p><p>In a multi-head attention, each attention head starts to learn a distinct job. For example:</p><ul><li><em>One head</em> learns to connect the subject of a sentence to its verb.<br><strong>“The dogs in the yard are barking.”<br></strong>An attention head relates the plural “dogs” to the linking verb “are”. The model correctly chooses “are” over. The Attention head also relates “barking” to “dogs.<br>The model discovers this pattern because it helps to reduce the loss when predicting the text.<br> As the model gets bigger, the behavior becomes clearer and more stable.</li><li><em>Another head</em> learns to connect to the correct pronouns.</li><li><em>Another head</em> aligns translations.<br>In language translation, word alignment means tracking which word in a language <strong>A</strong> corresponds to which word in language <strong>B</strong>?<br><strong>English</strong>: the black cat sat on the mat<br><strong>Spanish</strong>: el negro gato se sentó en la estera<br>A special attention head (cross-attention) learns to do this mapping:<br>When generating “negro”, it pays attention to “black”.<br>When generating “gato”, it pays attention to “cat”.<br>When generating “estera”, it looks at “mat”.<br>Transformers are not explicitly taught this!</li><li>Transformers don’t have explicit syntax tree rules. Example they are never told:<br>“which is a noun phrase”<br>“which verb attaches to a subject”<br>“which words form a clause”<br>Yet, some attention heads behave as if they are reading the syntax tree. This specialization is not programmed. It emerges purely from gradient descent.</li><li>Long-range reasoning suddenly appears<br>Small models struggle with long sentences and maintaining context over paragraphs. But, as the models become larger, the learned interactions between Query, Key, and Value vectors become richer, more structured, more specialized which leads to large jumps in the performance.</li></ul><p><strong>What is an attention head?<br></strong>An attention head is a computational block inside a transformer layer that performs scaled dot-product attention on a projected version of the input sequence. Each head has its<strong> </strong>own set of these matrices.</p><p><strong>What does one head do?</strong></p><ol><li>Projects the input into a different subspace(Q, K, V)</li><li>Computes similarity in that subspace</li><li>Extracts a different type of pattern</li></ol><p>Therefore, one head might capture:</p><ul><li>coreference (“he” means “John”)</li><li>syntax (“subject attends to verb”)</li><li>positional structure</li><li>translation alignment</li><li>punctuation dependencies</li><li>long-range vs short-range dependencies</li><li>Sometimes a single head can capture different semantics even if the head is re-trained on same parameters, but the overall behavior remains similar across the runs.</li></ul><p><strong>What is the need for multiple heads?</strong></p><p>With <em>n</em> heads, you have <em>n</em> separate attention mechanisms, each learning unique features. The outputs from all heads are concatenated, giving a richer representation for each token.<br>The model benefits when heads cover different aspects of the sequence.<br>Each attention head is not manually programmed, nor are they multiple copies of the same head. Every head has its own set of learned parameters (own Wq, Wk, Wv matrices).</p><p>All the attention heads use the same formula and perform the same operation, but because their weights differ, each head learns to focus on different patterns.</p><p>There is no manual rule like “Head 1 tracks syntax, Head 2 tracks coreference.” These patterns <strong>emerge beautifully during training</strong>.</p><p><strong>Sometimes multiple attention heads can also learn redundant pattern </strong><br>but, in large and well-trained transformers they usually end up learning different semantic roles because:</p><ul><li>Their weight matrices start randomly</li><li>Gradients push them to reduce loss by focusing on different cues. The loss is not defined separately for each head. All heads receive gradients from the same global loss, and they specialize emergently, not because each head has its own target.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*49SCjEhLZomynwg1LugjfA.jpeg" /><figcaption>Transformer explained with 3 heads</figcaption></figure><p><strong>Are Query (Q), Key(K), Value(V), vectors, matrices or tensors?<br></strong>· Q, K, V can be a vector for a single token.<br>· Matrix for <em>n</em> tokens.<br>· With batch or multiple heads, it becomes a 3D or 4D tensor.</p><blockquote>The emergent behaviors of Q, K, V vectors were not immediately known after the Transformers were introduced in 2017 (“Attention Is All You Need”). It took approximately 4–6 years!</blockquote><blockquote>We still don’t fully understand them; it’s an active research area!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fded3d15394" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/emergent-behavior-of-transformers-1fded3d15394">Emergent Behavior of Transformers</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision Digest — Issue #2]]></title>
            <link>https://ai.plainenglish.io/computer-vision-digest-issue-2-7606c5316296?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/7606c5316296</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 13:52:28 GMT</pubDate>
            <atom:updated>2025-12-15T15:22:46.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision Digest — Issue #2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*NZBxWXuGhLu3RArkAg-L5A.jpeg" /></figure><p>Welcome to the second issue of the Computer Vision Digest — a simple summary of important CV concepts and fun facts. This issue will cover:</p><p>Faster RCNN<br>Anchors and Region proposals concept<br>Mini Glossary<br>Fun Facts<br>Quiz</p><p><strong>Writer’s note:</strong><br><em>My journey into ML and specifically CV has been exciting and fun filled! Lots of interesting concepts and applications came my way. This is an attempt to share some of that with all of you. I have tried to distil the essence into an easy read so that learners without a deep background in ML can also understand the material. If your interest is piqued, references provided will allow you to dive deeper into the content. Happy Reading!</em></p><h3>Faster RCNN Algorithm</h3><p>Faster R-CNN is a two-stage object detection architecture that improves speed and accuracy by introducing a <strong>Region Proposal Network (RPN)</strong>.</p><p><strong>Stage1<br></strong>1. The image passes through the backbone CNN(VGG/ResNet) and produces a feature map.<br><strong>2.</strong> Then the RPN slides over these features and generates high-quality region proposals (candidate boxes). RPN is not a separate network, it is just extra convolution layers applied on top of the backbone’s feature map for further convolution on that feature map.</p><p><strong>During forward pass:</strong><br> The feature map is computed first; then RPN processes it.</p><p><strong>During training:</strong><br> The backbone’s feature map and RPN layers are learned <em>together</em> (in alternating steps).<br> Although RPN uses the feature map, gradients flow back through the backbone.</p><p><strong>Stage2<br></strong> <strong>ROI Pooling (Region of Interest Pooling)</strong> takes the feature maps of different-sized regions from an image and converts them into the same fixed size. These fixed size feature maps are then passed through two fully connected layers: classification head and Bounding Box regression head. These two heads run parallelly.</p><ul><li><strong>Classification head outputs </strong>which object class is present (dog / person / background etc.)</li><li><strong>Bounding box regression head pr</strong>edicts refined coordinates of the box giving the exact location of the object</li></ul><p>Faster R‑CNN is still used today, especially in research and applications where accuracy is more important than extreme speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*xpML6hI8cHVOnKKgrr7vxQ.jpeg" /><figcaption>Visualization from the Faster R-CNN paper (Ren et al., 2015) [arXiv:1506.01497]</figcaption></figure><h3><strong>Concept Highlight: Anchors and Region proposals</strong></h3><p><strong>Anchors</strong> are predefined, fixed shape bounding boxes placed uniformly across the image. It is just the starting box, doesn’t know anything about object. It just has the co-ordinates (x, y, width, height)</p><p><strong>Region proposals</strong>: RPN refines the anchor boxes to predict region proposals. They represent likely object locations. Anchors are like empty frames placed all over the image. Region proposals are like frames adjusted to fit the object</p><h3>Mini Glossary</h3><ul><li><strong>IoU</strong>: IoU (Intersection over Union) is a metric used to measure how much two bounding boxes overlap.</li><li><strong>Translation Invariant</strong>: Output does not change much if you shift (move) the inpit slightly in space. the model still recognizes it as the same object.</li><li><strong>Pyramid of images</strong>: collection of same image at different scales</li></ul><h3>Fun Facts</h3><ul><li>Dropout is like making your neurons play hide-and-seek during training.</li><li>Transformers actually don’t transform anything — they just pay attention really well.</li><li>When I first heard the word “Spatial” in a video, I thought they wrongly pronounced the word “Special”.</li></ul><h3>Quiz</h3><p><strong>1.</strong> What is the full form of COCO dataset?<br>2. What are multi-scale images?<br>3. What is SGD?</p><p><em>Ans1: COCO: Common Objects in Context<br>Ans2: Versions of the same image at different resolutions or sizes<br>Ans3: : Stochastic Gradient Descent(SGD) is an optimization algorithm used during backpropagation to update the model’s weights.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7606c5316296" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/computer-vision-digest-issue-2-7606c5316296">Computer Vision Digest — Issue #2</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LIME: A simple explanation]]></title>
            <link>https://ai.plainenglish.io/lime-a-simple-explanation-bfa7f92e040d?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa7f92e040d</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 16:05:12 GMT</pubDate>
            <atom:updated>2025-12-15T06:31:02.266Z</atom:updated>
            <content:encoded><![CDATA[<p>This document provides a simple explanation of LIME technique used in Machine Learning.</p><p>LIME (Local Interpretable Model-agnostic Explanations) is a technique to explain why a machine learning model made a specific prediction.</p><p>LIME creates a new dataset of perturbed inputs and then trains a new simple model (surrogate model) on that dataset to approximate the original model locally. Model-agnostic<strong> </strong>means it does not depend on model’s internal parameter or architecture. Just focuses only the input and output from model.</p><h3><strong>LIME for Images</strong></h3><p>Let us understand how LIME works when the input is an image. Suppose you feed a “CAT” image to your prediction model. And the model predicts that the image is a cat with 90% probability. Now, you might ask, “Why did the model think this is a cat?”. LIME is used to answer this question.</p><h4><strong>How LIME Works</strong></h4><p><strong>Step 1 — A new dataset is created</strong></p><p><strong>1.</strong> <strong>First break the image into simple chunks<br></strong>LIME divides the image into superpixels. A superpixel is a group of neighboring pixels that look similar and belong to the same region of an object. Instead of treating every single pixel separately (which would be thousands of features), each region is treated as one feature.</p><p>Eg: nose, ear, eyes, head, mouth, whiskers, body, background</p><p><strong>2</strong>. <strong>Create perturbed images<br></strong>A new image is created by removing one or more regions(superpixels) of the original image. LIME creates a whole dataset of such perturbed images.</p><p><strong>3.</strong> <strong>Learn importance from changes<br></strong>Every perturbed image is fed to the original (main) model to see how the prediction changes. This helps LIME to understand which regions of the original image are most crucial. Suppose eyes are removed, how much does the prediction probability drop. If it drops by 80% then that means that feature i.e. “eyes” in our case, is very important feature for the detection of a “cat”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*nmaKIPvWpWQ8wgS5yxV6pg.png" /></figure><p>The new dataset of LIME has perturbed images and also information on how each image affects the prediction</p><p>New dataset understands how prediction changes when we hide parts. This dataset represents the model’s behavior locally around one specific image.</p><p><strong>Step 2 — LIME trains a new model on this new dataset</strong></p><p>This model learns How does turning each superpixel ON or OFF affect the prediction? This is a small human-interpretable model that gives a simple explanation of what matters.</p><p>The output is a visual heat map shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*ufn5BSy0PmYDDP_IMUjfxQ.png" /></figure><ul><li>The yellow-outlined patches are the superpixels that increased the model’s confidence in the most likely class</li><li>Everything darkened around those areas means LIME hid those pixels to test their importance</li></ul><p>This heat map can be interpreted as: “eyes, ears and whiskers convinced the model that it’s a cat!”</p><h4><strong>Why is LIME needed?</strong></h4><p>It is very important to know what features influence the decision making in a model. Some of the uses are listed below:</p><ul><li>Feature selection and model improvement. Unimportant features that do not contribute to the decision making can be removed.</li><li>Debugging model errors. A model using wrong clues can be fixed. For example, a model is incorrect if it detects wolves only when there is snow in the background.</li><li>Trust and Transparency. Humans can trust a decision only when they understand why it happened.</li></ul><h4><strong>Sample code to generate LIME heatmap</strong></h4><pre>pip install lime tensorflow keras pillow scikit-image<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from lime import lime_image<br>from skimage.segmentation import mark_boundaries<br>from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions<br>from tensorflow.keras.preprocessing import image<br># Load pretrained model<br>model = VGG16(weights=&#39;imagenet&#39;)<br>model.predict(np.zeros((1, 224, 224, 3))) # warmup run<br># Load the cat image and preprocess<br>img_path = &quot;cat_lime.jpg&quot; # &lt;= PUT YOUR CAT IMAGE PATH HERE<br>img = image.load_img(img_path, target_size=(224, 224))<br>img_array = image.img_to_array(img)<br>img_batch = np.expand_dims(img_array, axis=0)<br>img_pre = preprocess_input(img_batch)<br># Define prediction function<br>def predict_fn(images):<br>images = preprocess_input(images)<br>return model.predict(images)<br># Create LIME explainer<br>explainer = lime_image.LimeImageExplainer()<br>explanation = explainer.explain_instance(<br>img_array.astype(&#39;double&#39;),<br>predict_fn,<br>top_labels=1,<br>hide_color=0,<br>num_samples=1000 # more samples = smoother heatmap<br>)<br># Get explanation mask for top prediction<br>top_label = explanation.top_labels[0]<br>temp, mask = explanation.get_image_and_mask(<br>top_label,<br>positive_only=True,<br>num_features=5,<br>hide_rest=False<br>)<br># Show the heatmap<br>plt.figure(figsize=(8, 8))<br>plt.imshow(mark_boundaries(temp / 255.0, mask))<br>plt.title(&quot;🔥 LIME Heatmap - Important Superpixels&quot;)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><h4><strong>Drawbacks of LIME</strong></h4><p>LIME’s main limitation is that it is “local”. It approximates a complex model with a simple model only around one input, which can lead to inaccurate or misleading explanations. Instead of trying to explain the entire model (global behavior), LIME explains the model’s decision only around the specific input instance.</p><p>Here are few more issues:</p><ul><li>Not Stable with repetitions. Running LIME multiple times on the same image can give different heatmaps.</li><li>Superpixels are not semantic. Image segments don’t have meaningful feature names. Sometimes the segments are random shapes or background.</li></ul><blockquote><strong>LIME is not perfect, but it is practical.</strong><br> LIME remains widely used due to its simplicity, model-agnostic nature, and ability to provide useful local interpretability for black-box models.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa7f92e040d" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/lime-a-simple-explanation-bfa7f92e040d">LIME: A simple explanation</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision Digest — Issue #1]]></title>
            <link>https://ai.plainenglish.io/computer-vision-digest-issue-1-03eab3f38658?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/03eab3f38658</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 12:43:21 GMT</pubDate>
            <atom:updated>2025-12-15T06:30:58.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision Digest <strong>— </strong>Issue #1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*NZBxWXuGhLu3RArkAg-L5A.jpeg" /></figure><p>Welcome to the first issue of the Computer Vision Digest — a simple summary of important CV concepts, techniques, code snippets, and quick quizzes. This issue will cover:</p><p>Bounding Box concept<br>Nearest Neighbour algorithm<br>Weights and Biases tool<br>Mini Glossary<br>Fun Facts<br>Quiz</p><p><strong>Writer’s note</strong>:<br><em>My journey into ML and specifically CV has been exciting and fun filled! Lots of interesting concepts and applications came my way. This is an attempt to share some of that with you. I have tried to distil the essence into an easy read so that learners without a deep background in ML can also understand the material. If your interest is piqued, references provided will allow you to dive deeper into the content. Happy Reading!</em></p><h3>Concept Highlight — Bounding Box</h3><p>Bounding box is usually shown as a rectangular box around the object with a label. It is used for object detection. This technique is faster and much less computationally expensive than semantic segmentation because segmentation works on pixel level.</p><p>Prior to CNN based technique, bounding boxes were obtained by sliding a window over the image, extracting hand-designed features, and using a classical classifier to decide if the window contained an object.</p><p>Deep learning replaced the hand-crafted features with learned features. A CNN-based detector proposes possible bounding box regions that might contain objects and not background. A bounding box regressor predicts the bounding box coordinates. Loss functions force the network to improve box accuracy over training. Each proposed region is also classified with class labels (dog, cat, car, background, etc.).</p><p>👉 <strong>Read full article in Medium:</strong> <a href="https://medium.com/@lalithasandeepraman/role-of-bounding-box-in-object-detection-261aed7c1f3e"><strong>Role of Bounding Box in Object Detection</strong></a></p><h3>Algorithm Spotlight — Nearest Neighbour (NN) classifier</h3><p>To predict the label for a new sample, find the most similar training sample and use its label.<br>Input data is first converted to a feature vector. A feature vector is a numerical representation of an object in an n-dimensional space. These numbers describe important characteristics such as shape, colour, texture etc.<br>CNNs automatically extracts these feature vectors.<br>Distance metrics such as, Euclidean distance, Manhattan distance or Cosine similarity are commonly used to check for similarity between two data points.<br>Find the distance between the new data point with every training data point.<br>The label of the nearest neighbour (closest distance) is assigned to the new data point</p><p>K — Nearest neighbour is an extension to the above algorithm. Here, instead of copying label from the nearest neighbour, a majority vote is taken from K closest points. K is a hyperparameter</p><h3>Tool to Know — Weights &amp; Biases (<a href="https://wandb.ai/)">https://wandb.ai/</a>)</h3><p>A powerful experiment-tracking tool for machine learning. It helps you log training metrics, compare model versions, visualize results, manage datasets, and collaborate with teammates — all in one dashboard. Perfect for machine learning experiments. You can automate to run your code for different parameter values and track the results. The visual results can also be used as reports.</p><h3>Mini Glossary</h3><ul><li><strong>Classification Head<br></strong>The network part that decides “what object is this?”</li><li><strong>Regression Head</strong><br>The network part that adjusts bounding box coordinates.</li><li><strong>Backbone</strong><br>The main CNN (like ResNet or VGG) used to extract features from an image.</li></ul><h3>Fun Facts</h3><ul><li><strong>YOLO got its name as a joke.<br></strong>“You Only Look Once” came from the idea that the model predicts everything in one pass instead of multiple stages.</li><li><strong>The word “objectness” didn’t exist before modern CV.<br></strong>It was coined to describe “how likely a region contains <em>any</em> object”.</li><li><strong>Convolution filters are just tiny number grids!<br></strong>Most people imagine convolution filters as something magical, but they are just small matrices filled with numbers (like 3×3 or 5×5).<br>During convolution, these numbers simply get multiplied with the pixel intensities under the filter and added up.</li></ul><h3>Quick Quiz</h3><p>1. What is Padding?<br>2. What do you mean by Stride<br>3. What are Anchor Boxes</p><p><em>Answer1: Extra pixels added around an image so that the output size doesn’t shrink after convolution.<br>Answer2: How many pixels the convolution filter moves at each step.<br>Answer3: Predefined box shapes (sizes + aspect ratios) used by detectors to predict object locations.</em></p><p><em>Thank you for reading the first edition. Stay tuned for the next digest with more CV concepts!</em></p><blockquote>For questions or suggestions, message me on Medium.<br>Follow me on Medium for future digests!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03eab3f38658" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/computer-vision-digest-issue-1-03eab3f38658">Computer Vision Digest — Issue #1</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Role of Bounding box in Object Detection]]></title>
            <link>https://ai.plainenglish.io/role-of-bounding-box-in-object-detection-261aed7c1f3e?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/261aed7c1f3e</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 21:01:55 GMT</pubDate>
            <atom:updated>2025-12-17T07:04:53.487Z</atom:updated>
            <content:encoded><![CDATA[<p>This document provides a high-level explanation about the role of bounding boxes in object detection, an important task in computer vision.</p><p>For an input image, bounding box is usually shown as a rectangular box around the object with a label. It is used for object detection. Bounding boxes don’t capture the exact shape, but they give a compact representation of an object’s position. This technique is faster and much less computationally expensive than semantic segmentation because segmentation works on pixel level.</p><p><strong>How Bounding Boxes Are Predicted</strong></p><ol><li>CNN extracts features from the image.<br>2. The model suggests potential bounding box regions that might contain objects and not background.<br>3. A bounding box regressor predicts four numbers (x, y, width, height) to refine the box coordinates. Loss functions force the network to improve box accuracy over training.<br>4. Each proposed region is also classified with class labels(dog, cat, car, background, etc.).<br>5. To avoid overlapping boxes for the same object, Non-Maximum Suppression (NMS) is used to keep only the most confident box.</li></ol><p><strong>Key Concepts</strong></p><ol><li><strong>Objectness score<br></strong>This score is a number between 0 and 1 to check if there is ANY object in the bounding box. It is a binary probability.<br><strong>1</strong> implies that this region definitely contains some object<br><strong>0</strong> implies that this region is definitely a background<br>It does <em>not</em> care what the object is.</li><li><strong>Class Probability</strong><br>Given that an object is present, the model then predicts the class, what object is it? For example:<br>probability that it’s a person<strong><br></strong>probability that it’s a dog<strong><br></strong>probability it’s a car, etc.<br>This is usually a softmax or sigmoid over all classes.</li><li><strong>Confidence Score</strong><br>Confidence combines both the ideas (Objectness × Class Probability). For example:<br>objectness = <strong>0.9<br></strong>class probability (dog) = <strong>0.7<br></strong>Confidence = 0.9 × 0.7 = <strong>0.63</strong></li><li><strong>Bounding box co-ordinates<br></strong>(Xmin,Ymin ,Xmax,Ymax) where,<br>Xmin,Ymin = top left corner of the box<br>Xmax,Ymax = bottom right corner of the box<br>These coordinates are predicted by regression using ground truth during training. The regression loss forces predicted coordinates to match the target.</li></ol><p><strong>Stages in object detection<br></strong>The object detection architecture can either be of two stages or of one stage.</p><p><strong>Two-Stage Detectors (Faster R-CNN, R-CNN, Fast R-CNN)<br></strong>Here, bounding box regression <strong>happens before</strong> classification.<br><strong>Stage 1: </strong>Proposes Bounding Boxes using Region Proposal Network (RPN)<br>The RPN (Region Proposal Network):<br>1. Predicts <strong>objectness</strong> (if it is an object or background)<br> High objectness means that the box likely contains an object.<br> Low objectness means that the box is background<br>2. Predicts bounding box regression offsets<br>3. Outputs around 200–2000 proposal boxes</p><p><strong>Stage 2: C</strong>lassifies along with final box refinement<br>1. From the proposed regions, ROI Align extracts a fixed-size feature map.<br>2. ROI head predicts the class.<br>3. Overlapping boxes of the same class are suppressed. Only the highest-scoring box is kept</p><p><strong>One-Stage Detectors (YOLO, SSD, RetinaNet)<br></strong>· One-stage detectors do <strong>not</strong> separate region proposal and classification.<br>· Everything happens in <strong>one pass</strong>. Bounding box regression and classification are predicted <strong>in parallel</strong> from the same features.</p><p><strong>Uses of Bounding Box:<br></strong>· Object Detection — To locate and classify objects (e.g., cars, dogs, people).<br>· Tracking — Follow objects across frames in videos.<br>· Medical Imaging — Highlight regions of interest (e.g., tumors).<br>· Autonomous Driving — Identify pedestrians, traffic lights, etc.</p><p><strong>Sample code</strong></p><p>This code is specifically for people detection. Bounding box is drawn around the people in the image.</p><pre>&quot;&quot;&quot;<br>Robust Faster R-CNN face detection runner with fallbacks and clear error messagesUsage:<br>  - Place your image as `input.jpg` (or change IMAGE_PATH)<br>  - If you have a Faster R-CNN face checkpoint, name it `face_fasterrcnn.pth` (or change CHECKPOINT_PATH)<br>  - python run_face_detector.py<br>&quot;&quot;&quot;</pre><pre>import os<br>import sys<br>import cv2<br>import torch<br>import numpy as np</pre><pre>IMAGE_PATH = &quot;input.jpg&quot;                # change if you use different name<br>CHECKPOINT_PATH = &quot;face_fasterrcnn.pth&quot; # change to your checkpoint path if available<br>OUTPUT_PATH = &quot;output_fasterrcnn.jpg&quot;<br>USE_MTCNN_FALLBACK = True               # if True, use MTCNN if no face checkpoint</pre><pre>def list_files_cwd():<br>    print(&quot;Files in current directory:&quot;)<br>    for f in os.listdir(&quot;.&quot;):<br>        print(&quot;  &quot;, f)<br>    print(&quot;------&quot;)</pre><pre>def draw_boxes_and_save(img_bgr, boxes, scores=None, labels=None, out_path=OUTPUT_PATH, th=0.5):<br>    for i, box in enumerate(boxes):<br>        x1, y1, x2, y2 = [int(v) for v in box]<br>        score = None if scores is None else float(scores[i])<br>        if score is not None and score &lt; th:<br>            continue<br>        cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>        label_text = &quot;&quot;<br>        if labels is not None:<br>            label_text += str(labels[i])<br>        if score is not None:<br>            label_text += f&quot; {score:.2f}&quot;<br>        if label_text:<br>            cv2.putText(img_bgr, label_text, (x1, max(15, y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)<br>    cv2.imwrite(out_path, img_bgr)<br>    print(f&quot;Saved output to: {out_path}&quot;)</pre><pre>def run_custom_fasterrcnn(img_bgr, img_tensor, checkpoint_path, device):<br>    import torchvision<br>    from torchvision.transforms import functional as F</pre><pre>    # Create model architecture for 2 classes (background + face)<br>    model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=None, num_classes=2)<br>    state = torch.load(checkpoint_path, map_location=device)<br>    # handle if checkpoint is a dict with &#39;model&#39; or state_dict<br>    if isinstance(state, dict) and &#39;model&#39; in state:<br>        state = state[&#39;model&#39;]<br>    try:<br>        model.load_state_dict(state)<br>    except Exception as e:<br>        print(&quot;Error loading checkpoint into model:&quot;, e)<br>        raise</pre><pre>    model.to(device).eval()<br>    with torch.no_grad():<br>        outputs = model([img_tensor.to(device)])[0]<br>    boxes = outputs[&#39;boxes&#39;].cpu().numpy()<br>    scores = outputs[&#39;scores&#39;].cpu().numpy()<br>    # labels probably all &#39;1&#39; (face) if trained that way<br>    labels = outputs.get(&#39;labels&#39;, None)<br>    if labels is not None:<br>        labels = labels.cpu().numpy()<br>    return boxes, scores, labels</pre><pre>def run_coco_fasterrcnn(img_bgr, img_tensor, device):<br>    # COCO pretrained model (detects &#39;person&#39; and many other objects)<br>    import torchvision<br>    model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=&quot;DEFAULT&quot;)<br>    model.to(device).eval()<br>    with torch.no_grad():<br>        outputs = model([img_tensor.to(device)])[0]<br>    boxes = outputs[&#39;boxes&#39;].cpu().numpy()<br>    scores = outputs[&#39;scores&#39;].cpu().numpy()<br>    labels = outputs[&#39;labels&#39;].cpu().numpy()  # COCO label ids<br>    return boxes, scores, labels</pre><pre>def run_mtcnn(img_bgr):<br>    # Lightweight face detector fallback (no checkpoint needed). Requires &#39;mtcnn&#39; package.<br>    try:<br>        from mtcnn import MTCNN<br>    except Exception as e:<br>        print(&quot;MTCNN not available. Install with `pip install mtcnn` to use fallback. Error:&quot;, e)<br>        raise<br>    detector = MTCNN()<br>    img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)<br>    results = detector.detect_faces(img_rgb)<br>    boxes = []<br>    scores = []<br>    for r in results:<br>        x, y, w, h = r[&#39;box&#39;]<br>        boxes.append([x, y, x+w, y+h])<br>        scores.append(r.get(&#39;confidence&#39;, 1.0))<br>    return np.array(boxes), np.array(scores), None</pre><pre>def main():<br>    print(&quot;Starting detector...&quot;)<br>    list_files_cwd()</pre><pre>    if not os.path.exists(IMAGE_PATH):<br>        print(f&quot;ERROR: Image file not found: {IMAGE_PATH}&quot;)<br>        print(&quot;Put your test image in the current directory or change IMAGE_PATH variable.&quot;)<br>        sys.exit(1)</pre><pre>    img_bgr = cv2.imread(IMAGE_PATH)<br>    if img_bgr is None:<br>        print(f&quot;ERROR: Failed to read image (corrupt or unsupported): {IMAGE_PATH}&quot;)<br>        sys.exit(1)</pre><pre>    # prepare tensor<br>    from torchvision.transforms import functional as F<br>    img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)<br>    img_tensor = F.to_tensor(img_rgb)</pre><pre>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    print(&quot;Using device:&quot;, device)</pre><pre>    # If checkpoint exists, try using custom Faster R-CNN face model<br>    if os.path.exists(CHECKPOINT_PATH):<br>        print(&quot;Found checkpoint:&quot;, CHECKPOINT_PATH)<br>        try:<br>            boxes, scores, labels = run_custom_fasterrcnn(img_bgr, img_tensor, CHECKPOINT_PATH, device)<br>            print(&quot;Detections from custom Faster R-CNN:&quot;, len(boxes))<br>            draw_boxes_and_save(img_bgr.copy(), boxes, scores, labels, out_path=OUTPUT_PATH)<br>            return<br>        except Exception as e:<br>            print(&quot;Failed to run custom checkpoint. Error:&quot;, e)<br>            # fallthrough to other options</pre><pre>    # If no checkpoint, use COCO pretrained model as fallback (detects &#39;person&#39; class)<br>    try:<br>        print(&quot;No custom checkpoint found, using COCO Faster R-CNN as fallback (detects &#39;person&#39; class among many).&quot;)<br>        boxes, scores, labels = run_coco_fasterrcnn(img_bgr, img_tensor, device)<br>        # if you only want &#39;person&#39; class (COCO id 1)<br>        # keep only label == 1<br>        person_mask = (labels == 1)<br>        boxes = boxes[person_mask]<br>        scores = scores[person_mask]<br>        labels = labels[person_mask]<br>        print(f&quot;Person detections: {len(boxes)} (filtered from COCO outputs)&quot;)<br>        draw_boxes_and_save(img_bgr.copy(), boxes, scores, labels, out_path=OUTPUT_PATH)<br>        return<br>    except Exception as e:<br>        print(&quot;COCO Faster R-CNN failed or torchvision model not available. Error:&quot;, e)</pre><pre>    # Final fallback: MTCNN face detector (no checkpoint required)<br>    if USE_MTCNN_FALLBACK:<br>        try:<br>            print(&quot;Attempting MTCNN fallback for face detection (install mtcnn if needed).&quot;)<br>            boxes, scores, labels = run_mtcnn(img_bgr)<br>            print(&quot;MTCNN detections:&quot;, len(boxes))<br>            draw_boxes_and_save(img_bgr.copy(), boxes, scores, labels, out_path=OUTPUT_PATH)<br>            return<br>        except Exception as e:<br>            print(&quot;MTCNN fallback failed. Error:&quot;, e)</pre><pre>    print(&quot;All detection options failed. Please ensure you have either:&quot;)<br>    print(&quot;  1) input.jpg in current dir, and&quot;)<br>    print(&quot;  2) a valid face_fasterrcnn.pth checkpoint (model.state_dict())&quot;)<br>    print(&quot;Or install mtcnn and let the fallback run:&quot;)<br>    print(&quot;  pip install mtcnn&quot;)<br>    print(&quot;Or use a pretrained COCO Faster R-CNN (no checkpoint required), but note COCO has no &#39;face&#39; class.&quot;)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Code Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fABlVAi_UZCVUdcG7M-auw.jpeg" /><figcaption>The model has detected the tiniest and farthest person in the image above:</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=261aed7c1f3e" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/role-of-bounding-box-in-object-detection-261aed7c1f3e">Role of Bounding box in Object Detection</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segmentation flow diagram]]></title>
            <link>https://medium.com/@lalithasandeepraman/segmentation-flow-diagram-22ec301464ee?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ec301464ee</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 09:15:03 GMT</pubDate>
            <atom:updated>2025-12-20T16:38:32.694Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A process diagram offering an overview of the segmentation workflow and serving as a quick reference for its key components.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgO8_QhXJzPNluRXtWhdcA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ec301464ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Segmentation in Computer Vision]]></title>
            <link>https://ai.plainenglish.io/image-segmentation-in-computer-vision-7d7d3388983b?source=rss-7b3b21471452------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7d3388983b</guid>
            <dc:creator><![CDATA[Lalitha Raman]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 10:50:54 GMT</pubDate>
            <atom:updated>2025-12-17T07:05:28.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Segmentation</h3><p>This document provides a high-level overview of segmentation in the field of Computer Vision.</p><p>Segmentation divides an image into similar regions. These regions help a machine to interpret an image like humans do. It also identifies the exact location of an object to the level of pixel position of the object.</p><h4>Types of Segmentation</h4><p>Segmentation is commonly classified into three main types as <strong>semantic</strong>, <strong>instance</strong> and <strong>pantopic</strong>. Superpixel segmentation is another type that is usually used as preprocessing for higher level tasks.</p><p><strong>1. Semantic Segmentation</strong></p><p>Suppose there is an image of a cat playing in an open field. The image shows sky, a cat, grass and trees. In our example, every pixel of the input image is categorized into sky, cat, grass or trees. These categories are class labels. A unique color is assigned to each category. Let’s say, the class label has the following legend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*P_q4YCiYlwPd4HowUC3ylQ.png" /></figure><p>The input image of a cat (as shown below) will look like this after semantic segmentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*TLA5uSXiEaizv-3H2DrB6Q.png" /></figure><p>Semantic segmentation as the name suggests is based on the meaning of each pixel. Each pixel gets a label using CNN.</p><p><strong>Use cases</strong></p><ul><li>In medical imaging for example, semantic segmentation does pixel level labeling of scans.</li><li>In auto driving cars, segmentation helps the car to identify its surroundings.</li><li>In satellite images, segmentation helps to analyze large scale geographical areas.</li></ul><p><strong>2. Instance segmentation</strong></p><p>In case there were 2 dogs in our input image, semantic segmentation cannot separate the 2 dog entities. Both the dogs will be shown as yellow. This is a probable issue because you cannot differentiate the 2 pink blobs in the image after segmentation. And, if both the dogs are close by then a big combined pink blob of both the dogs will be seen. This issue is overcome by instance segmentation.</p><p>In <strong>instance segmentation</strong>, every instance of the foreground object in the image is segmented separately. In our example, if there were 2 dogs then each dog would be segmented and color coded separately. The background, i.e. sky, field, road etc. are not labeled.</p><p>Instance segmentation also reduces computation power. Suppose we were only interested in dogs and not in other regions in the image like sky, trees etc., separating out the dog image for further processing reduces computational cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*-FHd1gdb6w92ElE-PuBrKw.png" /></figure><p><strong>Use</strong> <strong>cases</strong></p><ul><li>Friends in a picture. Each person in the image will be segmented with a unique color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*3t0PSjIW3OpwinALhC13CQ.jpeg" /></figure><ul><li>CCTV image with multiple people. Semantic segmentation will just say pixels of people. But instance segmentation will identify each individual person.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*E_kVVmuHf3idgOSXFzNU0Q.png" /></figure><ul><li>X-Ray of a fractured wrist might have multiple overlapping bones. Instance segmentation will separate out all the bones (radius, ulna, carpal bones etc.) along with precise measurements of each.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*7nyg6YPijuoY9QengoGllw.png" /></figure><ul><li>In a medical image (pathology image of breast tissue, there are hundreds of overlapping nuclei. Semantic segmentation will label the whole region as tumour. Whereas instance segmentation, detects and labels each nucleus separately measuring size, shape and density of each tumor separately.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*h87syV2vo1GQYWpSzNlNKg.png" /></figure><p><strong>3. Panoptic segmentation</strong></p><p>This is a combination of both semantic and instance segmentation. Every pixel gets a label and each foreground object gets an instance id. This type of segmentation is more precise.</p><p>The background is called “stuff” which is amorphous like water, sky, road, grass etc. Anything that does not have a clearly defined shape.</p><p>The foreground is called “things” which are countable like people, dogs, cars etc.</p><p><strong>4. Superpixel segmentation</strong></p><p>Superpixel segmentation divides an image into small, meaningful superpixel patches. A small group of neighbouring pixels that have similar properties like colour, brightness, or texture are called <strong>superpixel</strong>. It does not use deep learning for image processing.</p><h3>Summary</h3><p>The choice of algorithm depends on a few factors like domain, the nature of segmentation task, dataset size, hardware constraints, speed, accuracy, required features, evaluation metrics etc.</p><h3>Sample code</h3><pre>import torch<br>from torchvision import models, transforms<br>from PIL import Image<br>import matplotlib.pyplot as plt<br>import numpy as np<br># - - - - - - - - - - - - - - - -<br># Load pretrained DeepLab model<br># - - - - - - - - - - - - - - - -<br>model = models.segmentation.deeplabv3_resnet50(pretrained=True)<br>model.eval()<br># - - - - - - - - - - - - - - - -<br># Preprocess the input image<br># - - - - - - - - - - - - - - - -<br>preprocess = transforms.Compose([<br>transforms.Resize((520, 520)),<br>transforms.ToTensor(),<br>transforms.Normalize(mean=[0.485, 0.456, 0.406],<br>std=[0.229, 0.224, 0.225]),<br>])<br># Load an image (replace &#39;cat.png&#39; with your image path)<br>img_path = &quot;cat.png&quot;<br>input_image = Image.open(img_path).convert(&quot;RGB&quot;)<br>input_tensor = preprocess(input_image).unsqueeze(0) # add batch dimension<br># - - - - - - - - - - - - - - - -<br># Run the model<br># - - - - - - - - - - - - - - - -<br>with torch.no_grad():<br>output = model(input_tensor)[&quot;out&quot;][0]<br>output_predictions = output.argmax(0)<br># - - - - - - - - - - - - - - - -<br># Visualize results<br># - - - - - - - - - - - - - - - -<br># Random color map for each class<br>num_classes = output.shape[0]<br>colors = np.random.randint(0, 255, size=(num_classes, 3), dtype=np.uint8)<br># Create a color mask<br>segmentation_map = colors[output_predictions.numpy()]<br># Show input and segmented image<br>plt.figure(figsize=(12, 5))<br>plt.subplot(1, 2, 1)<br>plt.title(&quot;Original Image&quot;)<br>plt.imshow(input_image)<br>plt.axis(&#39;off&#39;)<br>plt.subplot(1, 2, 2)<br>plt.title(&quot;Semantic Segmentation&quot;)<br>plt.imshow(segmentation_map)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><p><strong>Code output</strong></p><p>Segmentation output for some sample pictures are given below for reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*IuzvOIJt49yVZy3jThUY8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*2itSvGSqG7916TXbnAexhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pNP6Yw1YgtY9Xkt2HrOoIg.png" /></figure><h3>Image Credits</h3><p>Images in this document have been sourced from various websites on the internet for illustrative and educational purposes only. All rights to the respective images belong to their original owners.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7d3388983b" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/image-segmentation-in-computer-vision-7d7d3388983b">Image Segmentation in Computer Vision</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>