<?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 Pranjal Datta on Medium]]></title>
        <description><![CDATA[Stories by Pranjal Datta on Medium]]></description>
        <link>https://medium.com/@pranjaldatta99?source=rss-654c86de54f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*naFBve52iWh-aX1P4piJrw.jpeg</url>
            <title>Stories by Pranjal Datta on Medium</title>
            <link>https://medium.com/@pranjaldatta99?source=rss-654c86de54f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:36:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranjaldatta99/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[One year of writing software in Go]]></title>
            <link>https://medium.com/@pranjaldatta99/one-year-of-writing-software-in-go-33b6aa2de2ce?source=rss-654c86de54f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/33b6aa2de2ce</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pranjal Datta]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 17:37:55 GMT</pubDate>
            <atom:updated>2024-10-18T17:37:55.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*gPEfXx7vB3rJgQXB.jpg" /><figcaption>Source: <a href="https://go.dev/blog/gopher">https://go.dev/blog/gopher</a></figcaption></figure><p>A year ago, I started writing my first professional project in Go. Until then, I had never written a single line of this programming language. Most of my prior work has always been in Python and Java. This article summarises my experience with the language, peppered with some opinions here and there. However, this is not an <em>opinion and judgement on the language</em>. This is also not a guide on how to learn Go.</p><p>So here we go.</p><h3>Syntax and Go’s simplicity</h3><p>Go prides itself on being <em>simple</em>. You can pick up the language syntax, idioms and <em>gotchas</em> within a few days at best and a week at worst. If you are coming from a dynamically typed PL background (like Python in my case), it might take you slightly longer, but if you are coming from a statically typed PL background, like Java, skilling up in Go would be a breeze.</p><p>This brings me to my second point. It’s very easy to mistake Go’s simplicity for a weakness. Coming from a Python background, I was missing the three ways to set up your environment, the multiple coding standards and packages that <em>did a lo</em>t. (Where are my sync <em>and async</em> methods?) At some level, I felt that the language’s simplicity would be the bottleneck in solving the problem(s) at hand.</p><p>In hindsight, I was so wrong. Go’s extraordinary power is its simplicity and ease of use. I would highly recommend this talk by Rob Pike, who covers why and how Go is simple.</p><p>The fact that Go is simple doesn’t stop you from solving complex problems. The correct way of writing Go code is <em>to think simply and break complex chunks into simpler chunks</em>.</p><p>Some of the nastiest tech debt that I introduced in my Go project in the earlier days was because I brought my Python way of thinking into the project.</p><h3>Consistency</h3><p>There’s one way of formatting Go code; the specification comes from the language itself (`go fmt`). No matter what codebase we are talking about, they look the same — no debates about camel-case vs snake-case, tabs vs spaces, whitespaces, etc.</p><p>There’s also only one way to manage Go packages and projects. Project dependencies are specified in go.mod. Packages are added to a project via `go install`, and that’s it.</p><p>I usually work on both Go and Python projects, and every time I use Pip or Conda, I miss Go’s package management.</p><p>Also, in a corporate setup, you are more often than not using proprietary packages. In Python, you have two options to accomplish this: you either vendor in the package or host your internal registry. In Go, you can install it straight from your internal Git repository. It makes life so much more enjoyable!</p><h3>Errors should always be returned as values</h3><p>This was the first time in my life that I came across the concept of returning errors as values. I love this concept so much that I have a hot take.</p><blockquote>Hot take: Try Catches should be illegal.</blockquote><p>Returning errors as values tell the programmer exactly which function can error and which cannot. This explicitly forces you to handle errors but also gives you the freedom to <em>decide</em> how to handle the error.</p><p>Due to a constraint violation, the DB layer failed to insert a row into the table. Check the error value and return an HTTP status code to the user. Did the CLI get an invalid option? Log the error and return a non-zero exit code.</p><p>You can neatly design your package to return from a list of possible errors that the caller can check.</p><p>The package <em>bar</em> defines a list of possible errors that any public function can return.</p><pre>package bar<br>var (<br> ErrBadRequest = errors.New(&quot;bad_request&quot;)<br> ErrInternal = errors.New(&quot;internal_error&quot;)<br>)<br>func DoSomething() (string, err) {<br> return &quot;&quot;, errInternal<br>}</pre><p>On the other hand, the caller package foo can check the error type and handle it appropriately.</p><pre>package foo<br>func main() {<br> s, err := bar.DoSomething()<br> if errors.Is(err, bar.ErrBadRequest) {<br> // Do something<br> }else if errors.Is(err, bar.ErrInternal) {<br> // Do something else<br> } else {<br> // Do a third thing, maybe panic?<br> }<br>}</pre><p>Compare this to the Python equivalent.</p><pre>def main():<br> try:<br> s = bar.do_something()<br> except Exception as e:<br> if isinstance(e, bar.ErrBadRequest):<br> # do something.</pre><p>This is so much cleaner than the Python equivalent. More importantly, it is easier for a new co-worker to understand. In the Python world, t<em>he only way to know whether or not a function can error is by relying on the documentation, which, if we are honest, can be a hit or miss</em>.</p><p>I also understand that this is a matter of taste. But my taste in this is strong.</p><h3>Interfaces and lack of inheritance</h3><p>Another shocker was the lack of inheritance. As someone whose education, undergrad and otherwise, revolved around OOPs and inheritance, I struggled to grasp the <em>why</em> behind interfaces and why one should <em>accept interfaces and returns structs</em>.</p><p>But it is the better way to program. Consumer functions define the interfaces they use, and producers return concrete types.</p><p>For example, let’s say we have a function, WriteData, in our service layer that attempts to create a new record in your data storage layer. Note that this layer can change from time to time — today, it is Postgres; tomorrow, it can be Mongo; the day after, it can be MySQL.</p><p>WriteData accepts an interface StoreWriter that defines the relevant methods. The function internally doesn’t care who or what type implemented that method as long as the type has defined methods that satisfy the interface.</p><pre>type StoreWriter interface {<br> InsertNewData(b []byte) error<br>}<br>func WriteData(s StoreWriter) error {<br> // some other stuff<br> return s.InsertNewData(b)<br>}</pre><p>Another great example is the Marshaller / Unmarshaller interface. Go’s standard library has the encoding/json package, the primary way Go projects convert structs to JSON and vice versa. The reliance on a pre-defined interface makes introducing custom marshalling and unmarshalling behaviour super easy. Simply add an Unmarshaland a Marshalmethod onto your struct that defines the custom behaviour. Another remarkable aspect is that nested structs can have their own custom marshalling and unmarshalling logic!</p><p>Writing unit tests with mocking becomes easy when your functions and methods accept interfaces.</p><p>I recommend going through the <a href="https://go.dev/tour/methods/9">Go Tour’s slides on interfaces</a>.</p><h3>Concurrency: Goroutines and channels</h3><p>Ah, concurrency! This is the highlight of articles and videos praising Go. While Go excels at concurrency — especially compared to Python — the key takeaway is the contrasting synchronisation approach.</p><p>Go recommends sharing memory and synchronising concurrent processes by <em>passing messages via channels</em>. Note that the standard library also implements a locking mechanism exposed via the <a href="https://go.dev/tour/concurrency/9)"><em>sync</em></a><em> </em>package, should a use-case demand it.</p><p>A lot has been said over the internet about Go’s concurrency, and it’s not productive to rehash all that again. <em>From my experience</em>, the whole message-passing construct is fantastic, simple and easy to reason about and maintain.</p><h3>Some closing thoughts</h3><p>Philosophically, programming languages represent the worldview of their creators and long-term maintainers. They are the culmination of a million decisions made by people in the project, each driven by some implicit and explicit factors, often not apparent to a casual user.</p><p>Go, above all, is a <em>professional tool.</em> It is designed and expected to make building software more efficient. It is a dead simple language with an extensive standard library and good enough DX.</p><p>Like all good and reliable tools, it stops being the concern and fades into the background. There is no bickering about ten different formatting styles (like JS and Python) or a steep learning curve with an almost academic rigour (like Rust).</p><p>As a language, Go often doesn’t inspire a lot of hot debate, and that’s a good thing. It’s a good, reliable tool that gets the job done. <em>It also helps by making coding really enjoyable</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33b6aa2de2ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why college isn't irrelevant]]></title>
            <link>https://medium.com/@pranjaldatta99/why-college-isnt-irrelevant-33aea7b75b45?source=rss-654c86de54f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/33aea7b75b45</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Pranjal Datta]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 09:17:49 GMT</pubDate>
            <atom:updated>2022-12-30T09:17:49.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qcqfgOs8coUkI357" /><figcaption>Why am I here? (Source: <a href="https://www.bankrate.com/">https://www.bankrate.com/</a>)</figcaption></figure><p>(<em>Originally published at </em><a href="https://pranjaldatta.github.io/2022/06/11/college/"><em>https://pranjaldatta.github.io/2022/06/11/college/</em></a><em> on 11th June, 2022</em>)</p><p>I recently completed my undergrad in CS Engineering and graduated. Like most of my peers around the world — past or present — during the course, I firmly believed in the irrelevance of college education (apart from being yet another checkbox in a status-driven society).</p><p>Now that I am on the other side, and with the benefit of hindsight, context, and more importantly, <em>distance from temporal and localized pain, </em>I&#39;ve come around 180 degrees — I think <em>college and your degree are relevant, probably more than ever.</em></p><p>This is a long read. I have provided a table of contents so that you can jump around. There&#39;s also a <em>summary</em> in the end for the folks interested in a quick read.</p><h3>Sections</h3><ul><li><a href="#54f7">Disclaimers and Assumptions</a></li><li><a href="#c2a7">Exposure</a></li><li><a href="#02ee">Peer Relationships</a></li><li><a href="#b32b">Alumni Network</a></li><li><a href="#a257">Brand and Mean Can-Do Index</a></li><li><a href="#b0f6">Go where your curiosity takes you</a></li><li><a href="#a435">Reality and the eternal cycle of suffering</a></li><li><a href="#4f9a">Bias and Incentives Online.</a></li><li><a href="#641e">Summary</a></li><li><a href="#cc46">Conclusion</a></li></ul><h3>Disclaimers and Assumptions</h3><p>The topic at hand is a pretty complicated and opinion-rich one. But more importantly, this is fundamentally a contextual topic. For example, the problems and issues of the higher education system in, say, the US doesn&#39;t translate in its entirety to the issues of the Indian Higher education system. Within the Indian context, too, sub-contexts are very important. Engineering disciplines have their own set of issues that have little overlap with, say, medical and liberal art disciplines.</p><p>It suffices to say that <strong>context and nuance are fundamentally crucial</strong> for topics like these<em>.</em></p><p>Hence below is the set of assumptions and disclaimers I hope you keep in mind while reading this article — so here goes,</p><ul><li><em>I am 22 years old at the time of writing and graduated a couple of weeks ago</em>. Take everything mentioned here with a two-pinches of salt. With time and experience, my opinions on this would most definitely change.</li><li><em>This article is primarily meant for B.Tech folks in India</em>. It would probably make little sense to people outside this limited context. If you are one of them, thanks for stopping by, and I hope you enjoy reading just for fun!</li><li><em>I am aware and actively trying to counter my survivorship bias.</em> I have been through the intense workload pressures and other stuff that make people mad about the system.</li><li><em>Most of the things mentioned here are personal lived experiences and observed experiences of peers.</em></li><li><em>There are a lot of nuances involved.</em> I will try to be explicit about the more obvious ones but it must be noted that it is not possible to account for <em>each and every nuance and subtlety.</em></li></ul><h3>Exposure</h3><p>Before we go ahead, let&#39;s define what I mean by a <em>background in the context of an 18-year-old fresher.</em></p><p><em>Background</em> for an 18-year-old is the number of family members and people in close familial proximity in engineering. Not just the degree, but <em>their career tracks too are in engineering</em>.</p><p>Now that the definition is established, let us carry on.</p><p>Very few people come from a family of engineers. Most people come from very non-technical / traditional backgrounds. Along with pretty much all of my friends, I belong to this category.</p><p><em>What is the issue here</em>? Well, frankly, we don&#39;t know much about the larger industry and, more importantly, the trends before college. Most of our decisions/plans before joining are driven by folklore, some of them being,</p><ul><li>The whole B.Tech -&gt; MBA -&gt; Investment Bank career track.</li><li>CS &gt;&gt; everything else.</li><li>Engineering &gt;&gt; everything else.</li><li>Working in software companies is painful, a source of unhappiness, full of regimentation, and everyone is just sad. (Thanks, Bollywood!)</li></ul><p>College is like a <em>buffet of exposure and experiences</em>. A couple of weeks in, you realize that careers can be in all shades of the color palette, beyond the black and white you thought it to be.</p><p>Batchmate who is programming for the first time is roommate with batchmate who has been programming since age 10? Check. Peers who want to stay in engineering roles vs. peers who found their calling in other non-tech domains? Check. An electrical engineer who transitioned into Software? Check. The friend who wants to join the military/IAS after graduation? Check. Batchmate joining the film industry after graduation? Check.</p><p>Your batch probably has people coming from all sorts of backgrounds. And everyone is trying to figure out what they want to do. Some would find their calling in the process, while the rest would carry on the search. <strong>But the fact that you spend four years of your life with fellow travelers on this journey exposes you to ways, means, and ideas you never knew could exist. And that&#39;s important.</strong></p><p>I know you are asking, &quot;But hey, what about Twitter and online communities?&quot;. Please read on to <em>The Bias and Incentives Online </em>section.</p><h3>Peer Relationships</h3><p>Colleges in India, especially those that admit students from all over the nation, are probably the best <em>socio-economic and cultural mixers. </em>For most people, it&#39;s perhaps the first time they are transplanted into a new environment outside their immediate familial environment — an unknown city, unfamiliar languages, and new cultures — and as a bonus, you are sharing rooms with strangers.</p><p>The only coping mechanism is to <em>make new friends. Some make a large number of them, some very few. The bottom line is that you build new relationships.</em></p><blockquote>More importantly, you have fun along the way!</blockquote><p>On a more serious note, all these relationships and experiences act as a <em>transformation function for everyone involved.</em></p><blockquote>Noone that I know of is the same person on their graduation day as they were on their commencement day.</blockquote><p>Like it or not, none of this can be replicated on online forums. Most people you meet online are “connections,” “followers,” and, at best, “acquaintances” — <em>Not friends.</em></p><h3>Alumni Networks</h3><p>Probably one of the most significant upsides of college. But more importantly, <em>this upside is directly proportional to the quality of your college and hence contributes significantly to the famous (or infamous) &quot;tiers.&quot;</em></p><p>Being from a higher tier (read: the IITs and BITS of the world) college with a strong, active, and high-quality alumni network across industries and research institutes makes your life relatively much easier. Referrals, information, and help come much more smoothly. Thanks to a pass-out senior, a friend of mine from one of these top institutes found it much easier to get in touch with a very sought-after professor at his dream lab in Canada.</p><p>Please note, <em>at no point am I insinuating</em> that kids from these colleges are somehow less deserving or somehow life is easy for them. It&#39;s not. These colleges are supremely competitive and demanding.</p><p>Also,<em> I am not insinuating</em> that colleges that are not IIT/BITS/NITs do not have such networks. My college does. So do other non-tier one colleges. I have benefited a lot from my college&#39;s alumni network. <em>It&#39;s all a question of how expansive and active the network is.</em></p><h3>Brand and Mean Can-Do Index</h3><p>Just a while ago, we mentioned the very emotive and dramatic (even controversial) word: &quot;<em>tiers.&quot;</em></p><p>We can go on and on about tiers and why they exist (or don&#39;t exist) or why they matter (or don&#39;t matter), but that&#39;s not why we are here.</p><p>The TLDR is as follows,</p><ul><li>Your college&#39;s brand is directly proportional to the number, variety, and quality of companies and roles coming on-campus.</li><li>The most significant value a <em>higher tier college </em>provides is that the <em>average kid</em> suffers from a <em>relatively lesser amount of inferiority complex and believes they can achieve or do much more. </em>It&#39;s a herd mindset game. This, in turn, has a <em>substantial impact on on-campus activities (technical or otherwise), which indirectly impacts the average student skillset.</em></li></ul><h3>Go where your curiosity takes you.</h3><p>College is an exciting place to be in. At any given point in time, multiple things are happening on campus.</p><p>Chances are there is a <em>club </em>for everything. Mars Rover? Yes. Race Car? Yes. Space Satellite team? Yes. Electric Race Car? Yes. Dirt Racing? Yes. MUNs and Public Speaking? Yes. Organisational committees for fests? Yes. Dance and Drama Clubs? Yes. Competitive Coding Clubs? Yes. — this list could go on. Even if there isn&#39;t one for your niche interest, very little stops you from starting one for your own niche needs!</p><p>The point is that college gives you a unique opportunity to work on multiple streams of interest — <em>at the same time. </em>You could spend the first half of the week working on fine-tuning the suspension of the racing vehicle that goes into testing next week while spending the last few days running around collecting sponsorships for the upcoming cultural fest! All the while squeezing in the time in-between for friends and other activities.</p><p><em>College is probably one of the few periods in life wherein you can take up or drop projects/work/interests on an ad-hoc, non-committal basis and try different things to find out what sticks. After all, engineering is more than grades and the degree in the end.</em></p><h3>Reality and the eternal cycle of suffering</h3><p>This section is the no-brainer one.</p><p>The reality of the world we live in (as of date) is that degrees are essential. 99% of open tech roles require an undergrad STEM degree. Life becomes easier when <a href="https://onlinevisas.com/usa/how-can-i-get-an-h-1b-visa-without-a-degree/">applying for work visas</a> if you have an undergrad degree. <em>The bottom line — </em>life is much more challenging without a degree. Of course, there would be exceptions, but edge-cases cannot guide our decision/opinion-making.</p><p>Another critical point against college is the suffering during the degree, namely, endless assignments, tests, limitations, administrative barriers, attendance requirements, etc.</p><p>I have been through the rigor and felt the same frustrations. But now that I am through, I have a slightly more evolved way of looking at this. If you are someone who isn&#39;t in your final semester (semester &lt; 8th), please skip this as it would read like utter bullshit.</p><p>My perspective on this has essentially evolved into this — all engineering batches, past, present, and future, have felt and will feel the same frustrations, so it&#39;s okay. You are not a particular case and consider this to be part and parcel of life. It sounds a lot like stoical resignation — but it&#39;s much more simple.</p><h3>Bias and Incentives Online</h3><p>Aha, the most controversial section of all!</p><p>If a martian were to judge the progress of human technology from #TechTwitter, it would seem that 95% of tech is <em>javascript, crypto, and leetcode. </em>This is, of course, is <em>sampling bias. </em>When dealing with social media of any kind, especially tech/ed/career twitter, the theory of <em>sampling bias </em>becomes fundamental.</p><p>So what is Sampling bias?</p><p>You can check out the <a href="https://en.wikipedia.org/wiki/Sampling_bias">Wikipedia article here</a>, but the essence is as follows,</p><blockquote>When a sampling technique is flawed such that the sampled set is biased towards certain members of the population which results in the mischaracterization of the underlying population — this bias is called Sampling bias.</blockquote><p>But again, why are we talking about Sampling bias?</p><p>My theory is that people (including myself) forget about this bias during their feed-scrolling sessions. As a result, you start misjudging the underlying population thanks to the bias in the reference sample. For example, a career in tech doesn&#39;t start and end with javascript — there are other things that people do as well.</p><p><em>None of the above are wrong in themselves. </em>All the three disciplines mentioned above are essential in their own right. The problem arises when people don&#39;t account for their own sampling bias and forget the unsaid ToC about social media — <em>the world doesn&#39;t start and end with what you see on your feeds.</em></p><p>Another critical point to keep in mind is a <em>conflict of interest, especially in the context of accounts with more significant followings. </em>If an account A is telling you that X is bad/sucks but also stands to gain financially by selling you Y, wherein Y is an antidote/competition/alternative to X, it&#39;s safe to assume that there is a bias and it is a potential case of a <a href="https://www.investopedia.com/terms/p/principal-agent-problem.asp#:~:text=The%20principal%2Dagent%20problem%20is,roles%20of%20principal%20and%20agent.">principal-agent problem</a>. An important thing to note here is that <em>I have essentially described capitalism, i.e., there is absolutely nothing wrong with identifying a problem and profiteering by selling its solution. All our modern economies are based on this simple concept.</em> It&#39;s also important to note that content creators play a critical role in pushing new products and services that often are better than the existing solutions. <strong>At the same time, while forming your opinions about an industry or anything in general from people on the internet, it helps to be mindful of potentially misaligned incentives.</strong></p><h3>Summary</h3><p>The TLDR is as follows,</p><ul><li>Please read the <em>Disclaimers and assumptions </em>before proceeding.</li><li>A college experience (for most kids coming from ordinary and modest backgrounds) introduces the 18-year-old fresher to a wide array of career trajectories and opportunities to switch between them.</li><li>Four years of undergrad is probably the best time to meet peers from all around the country, build relationships (not just professional, but of all kinds), and <em>have fun</em> :)</li><li>Access to an active and high-quality alumni network is an advantage in life. For a more lengthy explanation, please check out the <em>Alumni Network section.</em></li><li>A high-quality undergrad environment and peer groups generally lead to much better outcomes for the average student. On top of this, colleges with a better brand, more often than not, are a significant advantage, at least in the early days of your career. Again, for more verbosity, check out the <em>Brand and Mean Can-Do Index section.</em></li><li>The four years of your undergrad is an exciting opportunity to work on multiple interests — technical, creatives, people management, or whatever else might interest you. Hopefully, you will be able to figure out <em>what your thing is.</em></li><li>In reality, life is a lot harder without a degree. Exceptions exist, but exceptions and edge cases cannot be the primary north star.</li><li>Account for <em>sampling biases and principle-agent problems </em>while basing your opinions/approaches on social media commentary.</li></ul><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*CvRY6k7PE_6FpUmz.jpg" /><figcaption>Finally.</figcaption></figure><p>Finally, we are at the end of this one! <em>Pretty much all of this piece is essentially opinion based upon personal and observed experiences</em>. I could have added another section regarding j<em>ob hunting as a fresher,</em> but that would be stretching this article too far. More importantly, I feel that the topic is saturated with content.</p><p><em>It’s important to emphasize again that there are a lot of nuances that have been left unsaid in the paragraphs above.</em></p><p>I enjoyed writing this article a lot more than I expected. That could be because it helped me solidify most of my thoughts and ideas around this topic.</p><p>All in all, it was an excellent mental exercise! <em>I really hope you enjoyed reading this as much as I enjoyed writing this. More importantly, I hope this gave you some ideas to think about!</em></p><p>Feel free to write to me at <em>pranjaldatta99@gmail.com </em>with any feedback and counters!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33aea7b75b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Structural Similarity Index (SSIM): Theory + Code in PyTorch]]></title>
            <link>https://medium.com/srm-mic/all-about-structural-similarity-index-ssim-theory-code-in-pytorch-6551b455541e?source=rss-654c86de54f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6551b455541e</guid>
            <category><![CDATA[image-similarity]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[image-comparison]]></category>
            <dc:creator><![CDATA[Pranjal Datta]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 12:46:07 GMT</pubDate>
            <atom:updated>2021-03-04T06:50:32.379Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, while implementing a depth estimation paper, I came across the term <strong>Structural Similarity Index(SSIM)</strong>. SSIM is used as a metric to measure the <em>similarity </em>between two given images. As this technique has been around since 2004, a lot of material exists explaining the theory behind SSIM but very few resources go deep into the details, that too specifically for a gradient-based implementation as SSIM is often used as a loss function. Hence, this article is my humble attempt to plug this gap!</p><p>The objective of this article is two-fold,</p><ul><li>To explain the theory and intuition behind SSIM and explore some of its application in current cutting edge Deep Learning.</li><li>Go deep into a PyTorch implementation. You can skip to the code <a href="#abc2">here</a>. The full implementation can be found as a standalone notebook <a href="https://github.com/pranjaldatta/SSIM-PyTorch/blob/master/SSIM_notebook.ipynb">here</a>. Just click on the “Open in Colab” link to start running the code!</li></ul><p>So let’s begin!</p><h3>The Theory</h3><p>SSIM was first introduced in the 2004 IEEE paper, <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf"><em>Image Quality Assessment: From Error Visibility to Structural Similarity</em></a><em>. </em>The abstract provides a good intuition into the idea behind the system proposed,</p><blockquote>Objective methods for assessing perceptual image quality traditionally attempted to quantify the visibility of errors (differences) between a distorted image and a reference image using a variety of known properties of the human visual system. Under the assumption that human visual perception is highly adapted for extracting structural information from a scene, we introduce an alternative complementary framework for quality assessment based on the degradation of structural information.</blockquote><p><strong>Summary</strong>: The authors make 2 essential points,</p><ul><li>Most Image quality assessment techniques rely on quantifying errors between a reference and a sample image. A common metric is to quantify the difference in the values of <em>each of the corresponding </em>pixels between the sample and the reference images (By using, for example, <em>Mean Squared Error)</em>.</li><li>The <em>Human visual perception system </em>is highly capable of identifying structural information from a scene and hence identifying the <em>differences between the information</em> extracted from a reference and a sample scene. Hence, a metric that replicates this behavior will perform better on tasks that involve differentiating between a sample and a reference image.</li></ul><p>The Structural Similarity Index (SSIM) metric extracts 3 key <em>features </em>from an image:</p><ul><li><strong>Luminance</strong></li><li><strong>Contrast</strong></li><li><strong>Structure</strong></li></ul><p><em>The comparison </em>between the two images is performed on the basis of these 3 features.</p><p><em>Fig 1 </em>given below shows the arrangement and flow of the Structural Similarity Measurement system. <em>Signal X </em>and <em>Signal Y </em>refer to the Reference and Sample Images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBVkh54RJZrMsozG-vQdCQ.png" /><figcaption>Fig 1: The Structural Similarity Measurement System. Source: <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf">https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf</a></figcaption></figure><h4>But what does this metric calculate?</h4><p>This system calculates the <em>Structural Similarity Index</em> between 2 given images which is a value between -1 and +1. <em>A value of +1 </em>indicates that the 2 given images are <strong>very similar or the same </strong>while a <em>value of -1 </em>indicates the 2 given images are <strong>very different. </strong>Often these values are adjusted to be in the range [0, 1], where the extremes hold the same meaning.</p><p>Now, let’s explore briefly, how these features are represented mathematically, and how they contribute to the final SSIM score.</p><ul><li><strong>Luminance: </strong>Luminance is measured by <em>averaging </em>over all the pixel values. Its denoted by μ (Mu) and the formula is given below,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*bl5wmJc3XQtLAZmjDAywSA.png" /><figcaption>where xi is the ith pixel value of the image x. N is the total number of pixel values. Source: <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf">https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf</a></figcaption></figure><ul><li><strong>Contrast</strong>: It is measured by taking the <em>standard deviation (square root of variance) </em>of all the pixel values. It is denoted by σ (sigma) and represented by the formula below,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*l8cPwhPTvDEiuXcpBOjqPA.png" /><figcaption>Where x and y are the two images and mu is the mean of the pixel values of the image. Source: <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf">https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf</a></figcaption></figure><ul><li><strong>Structure</strong>: The structural comparison is done by using a consolidated formula (more on that later) but in essence, we divide the input signal with its <em>standard deviation</em> so that the result has unit standard deviation which allows for a more robust comparison.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*ORmcNjoh2VJ9KDfcvNItVA.png" /><figcaption>where x is the Input Image</figcaption></figure><p>So now we have established the mathematical intuition behind the three parameters. But hold on! We are not yet done with the math, a little bit more. What we lack now, are <strong>comparison functions</strong> that can <em>compare </em>the two given images on these parameters, and finally, a <strong>combination function </strong>that combines them all. Here, we define the comparison functions and finally the combination function that yields the <em>similarity index value</em></p><ul><li><strong>Luminance comparison function: </strong>It is defined by a function, <em>l(x, y)</em> which is shown below. μ (mu) represents the mean of a given image. x and y are the two images being compared.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*LIVHD8lyl-MTcNraFMTC7Q.png" /></figure><p>where C1 is a constant to ensure stability when the denominator becomes 0. C1 is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*GdwFuxTpz_CiBV57e_8-6Q.png" /></figure><p>Update: Throughout the article, we had not explored what the K and L constants in this equation are. Thankfully a reader pointed that out in the comments, and so in the interest of making this article a bit more helpful, I’ll just define them here.</p><p><em>L </em>is the dynamic range for pixel values (we set it as 255 since we are dealing with standard 8-bit images). You can read more about what are the different image types and what they mean, <a href="https://scikit-image.org/docs/dev/user_guide/data_types.html">here</a>.</p><p>K1, K2 are just normal constants, nothing much there!</p><ul><li><strong>Contrast comparison function: </strong>It is defined by a function <em>c(x, y)</em> which is shown below. σ denotes the standard deviation of a given image. x and y are the two images being compared.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*2WkH_iA3XA2q5rG-yjlRBQ.png" /></figure><p>where C2 is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*5qaoxTUPhfgEOpHashWoCQ.png" /></figure><ul><li><strong>Structure comparison function: </strong>It is defined by the function <em>s(x, y) </em>which is shown below. σ denotes the standard deviation of a given image. x and y are the two images being compared.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*El_5OKpZItY0UpJwgqbG3g.png" /></figure><p>where σ(xy) is defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*mtXPpPqoNbclC83rdwEDQw.png" /></figure><p>And finally, the SSIM score is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*PMKiq8VGf8g7objafz5sTw.png" /></figure><p>where α &gt; 0, β &gt; 0, γ &gt; 0 denote the relative importance of each of the metrics. To simplify the expression, if we assume, α = β = γ = 1 and C3 = C2/2, we can get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*zLdIPZ5_i4ju_nJ0-WmQ0g.png" /></figure><h3>But there’s a plot twist!</h3><p>While you would be able to implement SSIM using the above formulas, chances are it won’t be as good as the ready-to-use implementations available, as the authors explain that,</p><blockquote>For image quality assessment, it is useful to apply the SSIM index locally rather than globally. First, image statistical features are usually highly spatially nonstationary. Second, image distortions, which may or may not depend on the local image statistics, may also be space-variant. Third, at typical viewing distances, only a local area in the image can be perceived with high resolution by the human observer at one time instance (because of the foveation feature of the HVS [49], [50]). And finally, localized quality measurement can provide a spatially varying quality map of the image, which delivers more information about the quality degradation of the image and may be useful in some applications.</blockquote><p><strong>Summary: </strong>Instead of applying the above metrics <em>globally (i.e. all over the image at once)</em> it’s better to apply the metrics <em>regionally (i.e. in small sections of the image and taking the mean overall).</em></p><p>This method is often referred to as the <em>Mean Structural Similarity Index.</em></p><p>Due to this change in approach, our formulas also deserve modifications to reflect the same (it should be noted that this approach is more common and will be used to explain the code).</p><p>(<strong>Note: </strong>If the content below seems a bit overwhelming, no worries! If you get the gist of it, then going through the code will give you a much clearer idea.)</p><p>The authors use an 11x11 circular-symmetric Gaussian Weighing function (<em>basically, </em>an 11x11 matrix whose values are derived from a gaussian distribution) which moves pixel-by-pixel over the entire image. At each step, the local statistics and SSIM index are calculated within the local window. Since we are now calculating the metrics locally, our formulas are revised as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*duJlxI2vLLbUCDYij5HHEA.png" /></figure><p>Where <em>wi</em> is the gaussian weighting function.</p><p>If you found this a bit unintuitive, no worries! It suffices to imagine <em>wi</em> as a <em>multiplicand that is used to calculate the required values with the help of some mathematical tricks.</em></p><p>Once computations are performed all over the image, we simply take the <em>mean of all the local SSIM values </em>and arrive at the <strong>global</strong> SSIM value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*ntLs3Chom9Dx2BrlNHEwFA.png" /></figure><p>Finally done with the theory! Now onto the code!</p><h3>The Code</h3><p>Before we plunge into the code, it’s important to note that we won’t be going through <strong>every</strong> line but we will explore in-depth the essential ones. Let’s get started!</p><p>The full code can be found as a standalone notebook <a href="https://github.com/pranjaldatta/SSIM-PyTorch/blob/master/SSIM_notebook.ipynb">here</a>. Just click on the “Open in Colab” button to start running the code! The explanation in this section will be referring to the notebook mentioned above.</p><p>First, let’s explore some utility functions that perform some essential tasks.</p><h4>Function #1: gaussian(window_size, sigma)</h4><p>This function <em>essentially </em>generates a list of numbers (of <em>length equal to window_size</em>) sampled from a <strong>gaussian</strong> distribution. The sum of all the elements is equal to 1 and the values are normalized. <em>Sigma </em>is the standard deviation of the gaussian distribution.</p><p><strong>Note: </strong>This is used to generate the 11x11 gaussian window mentioned <a href="#602d">above</a>.</p><p><strong>Example:</strong></p><pre><strong>Code:</strong></pre><pre>gauss_dis = gaussian(11, 1.5)<br>print(&quot;Distribution: &quot;, gauss_dis)<br>print(&quot;Sum of Gauss Distribution:&quot;, torch.sum(gauss_dis))</pre><pre><strong>Output</strong>: </pre><pre>Distribution:  tensor([0.0010, 0.0076, 0.0360, 0.1094, 0.2130, 0.2660, 0.2130, 0.1094, 0.0360,0.0076, 0.0010]) </pre><pre>Sum of Gauss Distribution: tensor(1.)</pre><h4>Function #2: create_window(window_size, channel)</h4><p>While we generated a 1D tensor of gaussian values, the 1D tensor itself is of no use to us. Hence we gotta convert it to a 2D tensor (the 11x11 Tensor we talked about <a href="#602d">earlier</a>). The steps taken in this function are as follows,</p><ul><li>Generate the 1D tensor using the <em>gaussian function.</em></li><li>Convert it to a 2D tensor by cross-multiplying with its transpose (this preserves the gaussian character).</li><li>Add two extra dimensions to convert it to 4D. (This is only when SSIM is used as a loss function in computer vision)</li><li>Reshape to adhere to PyTorch weight’s format.</li></ul><pre><strong>Code:</strong></pre><pre>window = create_window(11, 3)<br>print(window.shape)</pre><pre><strong>Output: </strong></pre><pre>torch.Size([3, 1, 11, 11])</pre><p>Now that we have explored the two utility functions, let’s go through the main code! The core SSIM is implemented through the <em>ssim()</em> function which is explored below.</p><h4>Function #3: ssim(img1, img2, val_range, window_size=11, window=None, size_average=True, full=False)</h4><p>Before we move onto the essentials, let us explore what happens in the function <em>before</em> the ssim metrics are calculated,</p><ul><li>We set the maximum value of the normalized pixels (implementation detail; needn’t worry)</li><li>We initialize the gaussian window by means of the <em>create_window()</em> function IF a window was not provided during the function call.</li></ul><p>Once these steps are completed, we go about calculating the various values (the sigmas and the mus of the world) which are needed to arrive at the final SSIM score.</p><p><strong>Note: </strong>Since we are calculating local statistics <em>and </em>we need to make it computationally efficient, the formulas used are <em>slightly </em>different (They are just permutations of the formulas discussed above. Relevant mathematical materials are provided in the appendix.)</p><ul><li>We first calculate μ(x), μ(y), their squares, and μ(xy). <em>channels </em>here store the number of color channels of the input image. The <em>groups </em>parameter is used to apply a convolution filter to <strong>all</strong> the input channels. More information regarding <em>groups </em>can be found <a href="https://stackoverflow.com/questions/46536971/how-to-use-groups-parameter-in-pytorch-conv2d-function">here</a>.</li></ul><pre>channels, height, width = img1.size()</pre><pre>mu1 = F.conv2d(img1, window, padding=pad, groups=channels)<br>mu2 = F.conv2d(img2, window, padding=pad, groups=channels)</pre><pre>mu1_sq = mu1 ** 2<br>mu2_sq = mu2 ** 2</pre><pre>mu12 = mu1 * mu2</pre><ul><li>We then go on to calculate the squares of σ(x), σ(y), and σ(xy). For more math, check Appendix <a href="#091f">1.1</a>.</li></ul><pre>sigma1_sq = F.conv2d(img1 * img1, window, padding=pad, groups=channels) - mu1_sq</pre><pre>sigma2_sq = F.conv2d(img2 * img2, window, padding=pad, groups=channels) - mu2_s</pre><pre>sigma12 =  F.conv2d(img1 * img2, window, padding=pad, groups=channels) - mu12</pre><ul><li>Thirdly, we calculate the contrast metric according to the formula mentioned <a href="#8b06">here</a>,</li></ul><pre>contrast_metric = (2.0 * sigma12 + C2) / (sigma1_sq + sigma2_sq + C2)</pre><pre>contrast_metric = torch.mean(contrast_metric)</pre><ul><li>Finally, we calculate the SSIM score and return the mean according to the formula mentioned <a href="#54f7">here</a>.</li></ul><pre>numerator1 = 2 * mu12 + C1<br>numerator2 = 2 * sigma12 + C2<br>denominator1 = mu1_sq + mu2_sq + C1<br>denominator2 = sigma1_sq + sigma2_sq + C2</pre><pre>ssim_score = (numerator1 * numerator2) / (denominator1 * denominator2)</pre><pre>return ssim_score.mean()</pre><h4><strong>That was a lot! Now let’s see how the code performs!</strong></h4><p>We are going to test the code in three cases to check how does it perform. Let’s get going!</p><ul><li><strong>Case #1: True Image vs False Image</strong></li></ul><p>In the first scenario, we are going to run 2 <strong>very</strong> different Images through SSIM. One of them is considered the <em>True</em> Image while the other is considered the <em>False</em> Image. (Since we are measuring the <em>difference, </em>the Truth and Falsity labels are essentially interchangeable; They are being used only as reference points.)</p><p>The images are,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*v1dehLBw0gTIa1gQPyYhkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mmT016Yj9yZA5zBtHJnzvw.png" /><figcaption>False Image (left) True Image (Right)</figcaption></figure><p>The code below is for representation purposes only although not much different from the code in the notebook. For more detail and visualization, check the <a href="https://github.com/pranjaldatta/SSIM-PyTorch/blob/master/SSIM_notebook.ipynb">notebook</a>.</p><pre><strong>Code: </strong></pre><pre>img1 = load_images(&quot;img1.jpg&quot;) # helper function to load images<br>img2 = load_images(&quot;img2.jpg&quot;)</pre><pre>_img1 = tensorify(img1) # helper function to convert cv2 image to tensors </pre><pre>_img2 = tensorify(img2)</pre><pre>ssim_score = ssim(_img1, _img2, 225)<br>print(True vs False Image SSIM Score: &quot;, ssim_score)</pre><pre><strong>Output:</strong></pre><pre>True vs False Image SSIM Score: tensor(0.3385)</pre><ul><li><strong>Case #2: True Image vs True Image with Gaussian Noise</strong></li></ul><p>In this scenario, we compare the true image and a heavily noised version of it. The images are shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ImUacTRCA6-PumEZC0xw9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*PoK4XIlhisuaGxSycOXMEA.png" /><figcaption>The noised True Image (left), The true Image (Right)</figcaption></figure><p>On running the same piece of code as above we get,</p><pre><strong>Code: </strong></pre><pre>noise = np.random.randint(0, 255, (640, 480, 3)).astype(np.float32)<br>noisy_img = img1 + noise</pre><pre>_img1 = tensorify(img1)<br>_img2 = tensorify(noisy_img)</pre><pre>true_vs_false = ssim(_img1, _img2, val_range=255)</pre><pre>print(&quot;True vs Noised True Image SSIM Score:&quot;, true_vs_false)</pre><pre><strong>Output:</strong></pre><pre>True vs Noised True Image SSIM Score: tensor(0.0185)</pre><ul><li><strong>Case #3: True Image vs True Image</strong></li></ul><p>In the final case, we compare the True Image against itself. Hence, the image shown below is compared to itself. If our SSIM code is working perfectly, the <strong>score </strong>should be <strong>one.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mmT016Yj9yZA5zBtHJnzvw.png" /><figcaption>The True Image</figcaption></figure><p>On running the piece of code shown below, we can confirm that the SSIM score for this given scenario is indeed <strong>one.</strong></p><pre><strong>Code:</strong></pre><pre>_img1 = tensorify(img1)</pre><pre>true_vs_false = ssim(_img1, _img1, val_range=255)</pre><pre>print(&quot;True vs True Image SSIM Score:&quot;, true_vs_false)</pre><pre><strong>Output:</strong></pre><pre>True vs True Image SSIM Score: tensor(1.)</pre><h3>Conclusion</h3><p>Finally, we are here! In this article, we covered the theory behind SSIM and the code that goes into implementing it. In the References, some additional materials are provided including links to Computer Vision literature where SSIM is used in some form.</p><p>Hope understanding SSIM was much easier for you than it was for me :). I tried to focus on the areas that I personally found complicated and difficult to understand, hoping to not only consolidate my learnings but also in the process, help somebody else stumbling along the same path ;).</p><p>Would really appreciate feedback positive or negative. You can drop it in the comments section or reach out to me at <em>pranjaldatta99@gmail.com.</em></p><h3>References</h3><ol><li><em>The Original Pape</em>r: <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf">https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf</a></li><li><em>High-Quality Monocular Depth Estimation via Transfer Learning</em>: The depth estimation paper where SSIM is used as one of the loss functions. The paper can be found <a href="https://arxiv.org/abs/1812.11941">here</a>. You can also check my PyTorch Implementation of this paper <a href="https://github.com/pranjaldatta/DenseDepth-Pytorch">here</a>.</li><li><em>More on SSIM Applications: </em><a href="https://www.imatest.com/docs/ssim/">https://www.imatest.com/docs/ssim/</a></li></ol><h3>Appendix</h3><p><strong>1.0: </strong>Since using local statistics, the formula for the <em>mean (</em>μ), changes from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*moxHU8zJhJLzzH3NbuPJCg.gif" /></figure><p><strong>1.1: </strong>The variance (square of standard deviation) formula used in the Python code can be derived as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gd65BLt_LWKR1EmgeGZAvw.png" /></figure><p>While the derivation above shows the general method, in our context the final formula becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*1uLOcOs3yzjRvSRzacHSxw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6551b455541e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/srm-mic/all-about-structural-similarity-index-ssim-theory-code-in-pytorch-6551b455541e">All about Structural Similarity Index (SSIM): Theory + Code in PyTorch</a> was originally published in <a href="https://medium.com/srm-mic">SRM MIC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using PSPNet to change your background in under 40 lines of code]]></title>
            <link>https://medium.com/srm-mic/using-pspnet-to-change-your-background-in-under-40-lines-of-code-2faa9b5562d1?source=rss-654c86de54f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2faa9b5562d1</guid>
            <category><![CDATA[pspnet]]></category>
            <category><![CDATA[deep-learning-framework]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Pranjal Datta]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 08:35:30 GMT</pubDate>
            <atom:updated>2020-07-23T12:37:08.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XMJXQBX60oavUpqpXZ5Ow.png" /><figcaption>Virtual Backgrounds on Microsoft Teams. Image taken from <a href="https://www.crayon.com/en/news-and-resources/how-to-add-virtual-background-in-microsoft-teams/">https://www.crayon.com/en/news-and-resources/how-to-add-virtual-background-in-microsoft-teams/</a></figcaption></figure><p>Lately, thanks to global lockdowns, almost all of our lives whether at work or outside, have moved online. We conduct everything from work meetings to casual chat with friends and family over Zoom or any of the other multitude of similar such services. While these services pack in a lot of cool features and they have been evolving very rapidly keeping in mind their centrality in our COVID world, one such feature that has been used widely is the “virtual background”. For the uninitiated, this feature basically lets you add a custom background to your video feed, hiding all the details behind you that you would prefer the world didn’t see. Plus, it&#39;s a great way to add a bit of humor to those long meetings :)</p><p>The motivation for writing this blog is two-fold,</p><ol><li>Give a <strong>brief </strong>understanding of the technology behind this, i.e., <strong>Image Segmentation </strong>and exploring one such architecture, <strong>Pyramid Pooling Network (PSPNet) </strong>that accomplishes this.</li><li>How to implement this feature in &lt; 40 lines of code. For those who want to skip to the code, click <a href="#ef12"><strong>here</strong></a>.</li></ol><p>So, let&#39;s get started.</p><h3>Okay, so what are the buzzwords involved?</h3><ul><li><em>Classification</em>: It is probably the most fundamental task in Computer Vision. Basically, a <em>classifier</em> predicts <em>the class or category</em> to which the primary subject of the image belongs to. For example, the image below, if given as an input to a classifier would predict that it belongs to the category “cat”. <a href="https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd">This</a> is a great resource that goes into great depth on this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*QG_NyPQz49cBW3R-Dm83uw.jpeg" /><figcaption>A cat.</figcaption></figure><ul><li><em>Segmentation: </em>Segmentation is another fundamental task in Computer Vision. In essence, segmentation classifies <em>each pixel</em> into a category. To explore more, read this brilliant <a href="https://medium.com/@arthur_ouaknine/review-of-deep-learning-algorithms-for-image-semantic-segmentation-509a600f7b57">article</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*F6EfW7ZrcRV_HfPPg2GqWA.png" /><figcaption>The different types of segmentation. Image from <a href="https://towardsdatascience.com/review-deepmask-instance-segmentation-30327a072339">https://towardsdatascience.com/review-deepmask-instance-segmentation-30327a072339</a></figcaption></figure><p>Now that we have covered some of the basic terms involved, let us understand at a high-level what PSPNet is and what makes it special.</p><h3>Pyramid Scene Parsing Network (PSPNet): A Brief</h3><p><em>Disclosure: This description is going to be real brief. At the end of this article, I will be providing some brilliant resources that tackle PSPNet in great detail.</em></p><p>The PSPNet paper came <em>first</em> in the ImageNet Scene parsing Challenge, 2016, and was published in CVPR 2017. You can check how PSPNet performs on different benchmarks when compared with SOTA models, <a href="https://paperswithcode.com/paper/pyramid-scene-parsing-network">here</a>.</p><blockquote>Basically, PSPNet uses a <em>Pyramid Pooling Module</em> (more on this later) to gather <em>greater global context information </em>to make better pixel-level predictions.</blockquote><p>Before we go further, let&#39;s explore some of the terms mentioned here, what they mean and why they are important.</p><p><strong>Global Context Information</strong></p><p>In a nutshell, global context information can be interpreted as the “relationship” which a given object in a scene has with other objects in the scene. The paper talks about some issues that arise due to the absence of Global Context Information.</p><p><em>Inconspicuous Classes:</em></p><p>For example, in the picture below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*ZIumCxHEC3bE6I_ggQAUcw.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1612.01105v2.pdf">https://arxiv.org/pdf/1612.01105v2.pdf</a></figcaption></figure><p>Since the pillow and the bed have the same “pattern” or “appearance”, traditional segmentation networks that do not take global contextual information into account, would classify them into the same category. But, if we had knowledge about the relationship between the bed and the pillow, it would tell us that they belong to two different categories.</p><p><em>Confusion Categories:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*gRnYTZE-RWFkPt-FetOA2A.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1612.01105v2.pdf">https://arxiv.org/pdf/1612.01105v2.pdf</a></figcaption></figure><p>Often, if the network is unaware of the subset-superset relationship between object classes, it would predict classes with inconsistency. For example, some class object pairs like “dirt” and “soil”, “skyscraper” and “building” share a subset-superset relationship between them i.e. the building inside the yellow box above, can be either a skyscraper or a building but not both. Predicting the building inside the yellow box as a combination of patches of “building” and “skyscraper” does not make sense.</p><p><em>Mismatched Relationship :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*hXaDmjhkEuAjTRF82fCcFQ.png" /></figure><p>The boat within the yellow box cannot be classified as a “car” because the relationship between “cars” and “boats” tells us that cars don’t run on water(at least not until now). Hence, the network must understand the implicit contextual relationship between the object in the box and the river.</p><p>In fact, the <a href="https://arxiv.org/pdf/1612.01105v2.pdf">paper</a> produces a comparative graphic showing how a network (FCN) without global context information performs on these images against the proposed PSPNet architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2vTpAtim7SF_smv4XuEtg.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1612.01105v2.pdf">https://arxiv.org/pdf/1612.01105v2.pdf</a></figcaption></figure><p>As can be seen above, the results from the proposed architecture make more sense and are far more accurate.</p><p><strong>Pyramid Pooling Module</strong></p><p>The authors bring up an essential point in the paper,</p><blockquote>In a deep neural network, the size of the receptive field can roughly indicates how much we use context information. Although theoretically, the receptive field of ResNet [13] is already larger than the input image, it is shown by Zhou et al. [42] that the empirical receptive field of CNN is much smaller than the theoretical one, especially on high-level layers. This makes many networks not sufficiently incorporate the momentous global scenery prior. We address this issue by proposing an effective global prior representation.</blockquote><p>The point the authors are trying to make is that the receptive field (filter size) of most CNN’s is not large enough to capture effective global contextual information and to overcome this hurdle, they propose the <em>Pyramid Pooling Network</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emYC4xYASMLb5bSHNLZHOg.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1612.01105v2.pdf">https://arxiv.org/pdf/1612.01105v2.pdf</a></figcaption></figure><p><em>In a nutshell</em>, a Pyramid Pooling Network (PPM) “<a href="https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/">pools</a>” an input feature map at 4 different scales to collect contextual information at those scales and fuses them all to construct better feature maps that have greater global context information.</p><p><strong>(b) Feature Map</strong> is the output of the <a href="https://towardsdatascience.com/review-resnet-winner-of-ilsvrc-2015-image-classification-localization-detection-e39402bfa5d8">ResNet</a> Backbone using a dilated network strategy. By default, the size of the feature map (the number of channels) is 2048.</p><p><strong>(c) PPM</strong></p><ul><li><em>Step 1: </em><strong>Global Average Pooling</strong> is used to pool the input feature map to 4 different scales. In fact, each color code in the figure represents a pooling scale. The “<strong>Red</strong>” level is the coarsest level where the feature map is divided into <strong>1x1 sub-regions</strong>. The “<strong>orange</strong>” level divides the feature map into <strong>2x2 Sub-regions. </strong>The “<strong>blue” </strong>level divides it into <strong>3x3 sub-regions</strong> and the “<strong>green</strong>” level divides it into <strong>6x6 sub-regions</strong>.</li><li><em>Step 2</em>: Every pyramid level is followed by a <strong>1x1 convolutional layer</strong> to reduce the size of the feature map to 1/N of its original value where N is the number of pyramid levels (i.e. 4). For example, if the input feature map <strong>(b)</strong> has a size (no of filters) of 2048, at every level it will be reduced to 1/4*2048, i.e., 512. The authors suggest that this maintains the <strong>weight of global features</strong>.</li><li><em>Step 3</em>: Following Step 2, every lower dimension feature map is upsampled via “b<a href="https://datascience.stackexchange.com/questions/38118/what-is-the-difference-between-upsampling-and-bi-linear-upsampling-in-a-cnn">ilinear Interpolation</a>” to the dimensions of the <strong>(b) </strong>input feature map. For example, if <strong>(b) </strong>had a shape of <em>N x N x 2048</em>, after the upsampling stage, each pyramid level would have a feature map of dimensions <em>N x N x 512. </em>Finally, all the pyramid-level feature maps are concatenated with the input feature map <strong>(b)</strong> to produce the<em> final pyramid pooling global feature.</em></li></ul><p><strong>(d) Final Prediction</strong> is produced after passing the output feature map of the PPM Module through a final convolutional layer</p><p><strong><em>So to summarize, </em></strong>PSPNet gathers greater global contextual information regarding the image and the relationships between the objects in the image with the help of the Pyramid Pooling Module and other structural innovations to produce much more accurate segmentation results.</p><h3>How do Virtual Backgrounds work?</h3><p>Virtual Backgrounds work on the simple notion that the objects in a given scene can be considered as a part of the <em>foreground</em> or the <em>background </em>and hence they can be manipulated independently<em>.</em></p><p>While this in itself is subject matter for another article, in our context, we are concerned with replacing the “background” in a <em>given scene with people as the main foreground subject</em>. So our code should accomplish the following,</p><ul><li>Accept an image, “separate” out the <em>background </em>from the <strong>people</strong> in the <em>foreground.</em></li><li>Overlay the filtrate image from the step above onto the desired image which we want as the new background.</li></ul><h3>Finally, the code!</h3><p>Exploring the entire implementation of PSPNet, line by line is well beyond the scope of this article (and quite opposite the point of this article). In this section, we will see how we can use a Computer Vision library, <a href="https://github.com/pranjaldatta/PyVision"><em>PyVision</em></a>, to implement a pipeline that replaces the background in a few lines of code.</p><p>Let’s begin. We will be using Google’s <a href="https://colab.research.google.com/notebooks/intro.ipynb">Colaboratory</a>, well because, free GPU. <strong>The full notebook can be accessed </strong><a href="https://github.com/pranjaldatta/Quick-Background-Change/blob/master/ChangeBackground.ipynb"><strong>here</strong></a><strong>.</strong></p><p>For documentation, please refer <a href="https://github.com/pranjaldatta/PyVision/tree/master/pyvision/segmentation/pspnet">here</a>.</p><ul><li>First, we gotta clone the PyVision repository and the repository containing the sample images.</li></ul><pre>!git clone <a href="https://github.com/pranjaldatta/PyVision.git">https://github.com/pranjaldatta/PyVision.git</a><br>!git clone https://github.com/pranjaldatta/Quick-Background-Change.git</pre><ul><li>After making the necessary imports, we have to initialize the model. For more information regarding the parameters please refer to the links provided at the end of this article.</li></ul><pre>model = pspnet.PSPNet(model=&quot;pspnet-resnet101-voc2012&quot;, device=&quot;gpu&quot;, save=<strong>None</strong>, show=<strong>None</strong>, draw_map=<strong>False</strong>, draw_blend=<strong>False</strong>)</pre><ul><li>Now, our model is ready. For the purposes of this demo, we are using images that come with the Repository but feel free to use your own images for experimentation. We also call the <em>inference() </em>method to actually run inference on the input image and store the final predicted <strong><em>class map</em></strong> in the <em>preds </em>variable. The <strong><em>class map</em></strong><em> </em>stores the index of the class into which <em>each pixel</em> is classified. The “class name” of each pixel can be accessed from the “classes” variable using these indices.</li></ul><pre><em># storing the class list </em><br>classes = model.class_names<br><br>img_path = &quot;Quick-Background-Change/&quot;<br><br>preds = model.inference(img_path+&quot;test1.jpg&quot;, save=<strong>None</strong>)</pre><ul><li>Now, we have to <em>zero-out </em>all index values in the <em>preds</em> variable which refers to any class other than “person” (Because for our use-case any category other than “persons” is “background”). And all index values referring to “persons” are converted to 1.</li></ul><pre>index = classes.index(cls)</pre><pre><strong>for</strong> i <strong>in</strong> range(preds.shape[0]):<br>  <strong>for</strong> j <strong>in</strong> range(preds.shape[1]):<br>    <strong>if</strong> preds[i][j] != index:<br>      preds[i][j] = 0<br>    <strong>else</strong>:<br>      preds[i][j] = 1<br></pre><ul><li>Now, we have to invalidate <em>all</em> <em>pixels </em>that belong to any class other than “persons” but keep <em>all pixels </em>that belong to the “persons” class. We do this by multiplying the 2D image array with the <em>preds</em> variable which now acts as our mask (masking some values while revealing others).</li></ul><pre>img = Image.open(img_path+&quot;test1.jpg&quot;).resize((473, 473))<br><br>img = img * preds[..., <strong>None</strong>]<br>img = img.clip(0, 255)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*faRRAHf5YpnYxssptu5zuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*DuwLGS83zM71AMpTrb0tTQ.png" /><figcaption>Original Image (left) Image after masking (right)</figcaption></figure><ul><li>Now we have to load the <em>background</em> image. We also convert the <em>foreground</em> image to PIL format for ease of use.</li></ul><pre>foreground = Image.fromarray(img.astype(np.uint8)) <br>background = Image.open(img_path+&quot;scenery.jpeg&quot;).resize((473, 473))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*DuwLGS83zM71AMpTrb0tTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AoNfH3_k1nXGNVRL9PiHLg.jpeg" /><figcaption>Foreground Image (left) Background Image (Right)</figcaption></figure><ul><li>As the last step, we convert both the <em>foreground </em>and <em>background</em> images to NumPy arrays.</li></ul><pre>b , f = np.array(background), np.array(foreground)</pre><ul><li>We multiply the <em>background</em> image with the complement of <em>preds</em> to discard all <em>pixels from the background </em>that belongs to the class <em>persons</em>.</li></ul><pre>b = b * (1 - preds[...,<strong>None</strong>]</pre><ul><li>And finally, add and show!</li></ul><pre>new_img = cv2.add(b, f, dtype=cv2.CV_64F)<br><br>cv2_imshow(new_img[:,:,::-1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*Vdir-ZtG2Sjb_91LnDfUFA.png" /><figcaption>The final result</figcaption></figure><h3>Conclusion</h3><p>The <a href="https://github.com/pranjaldatta/Quick-Background-Change/blob/master/ChangeBackground.ipynb">notebook</a> which has the full code, of course, has code in a more structured manner and includes visualization. The total no of lines of code required is &lt;40.</p><p>The <em>effective </em>number of lines required for the <strong>core segmentation</strong> process is 3 (import + init model + run inference). Whereas, if we are to use the official <a href="https://github.com/hszhao/semseg">implementation</a>, not only the codebase required, runs into many more lines, its complex and the user needs to figure out a lot of complex moving parts to accomplish the same core segmentation task that was done here in 3 lines!</p><p>Hence, the objective of PyVision is to reduce the barrier to Computer Vision and make it easier for everyone! Hopefully, this article helped in getting a broad understanding of segmentation, PSPNet, and how virtual backgrounds are implemented.</p><p><em>P.S. Please contribute to PyVision so that it gets more populated with the most common and essential architectures that make Vision much easier and more accessible.</em></p><h3>References</h3><ol><li>The PSPNet paper: <a href="https://arxiv.org/pdf/1612.01105v2.pdf">https://arxiv.org/pdf/1612.01105v2.pdf</a></li><li>To read more about classifiers: <a href="https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd">https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd</a></li><li>This amazing blog going deep into PSPNet: <a href="https://towardsdatascience.com/review-pspnet-winner-in-ilsvrc-2016-semantic-segmentation-scene-parsing-e089e5df177d">https://towardsdatascience.com/review-pspnet-winner-in-ilsvrc-2016-semantic-segmentation-scene-parsing-e089e5df177d</a></li><li>This blog compares all the different segmentation architectures that have been proposed in the last few years: <a href="https://medium.com/@arthur_ouaknine/review-of-deep-learning-algorithms-for-image-semantic-segmentation-509a600f7b57">https://medium.com/@arthur_ouaknine/review-of-deep-learning-algorithms-for-image-semantic-segmentation-509a600f7b57</a></li><li>Learn more about ResNets here: <a href="https://towardsdatascience.com/review-resnet-winner-of-ilsvrc-2015-image-classification-localization-detection-e39402bfa5d8">https://towardsdatascience.com/review-resnet-winner-of-ilsvrc-2015-image-classification-localization-detection-e39402bfa5d8</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2faa9b5562d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/srm-mic/using-pspnet-to-change-your-background-in-under-40-lines-of-code-2faa9b5562d1">Using PSPNet to change your background in under 40 lines of code</a> was originally published in <a href="https://medium.com/srm-mic">SRM MIC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>