<?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[sausheong’s space - Medium]]></title>
        <description><![CDATA[My random ramblings on technology and other stuff - Medium]]></description>
        <link>https://medium.com/sausheong?source=rss----187e2cc596a4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>sausheong’s space - Medium</title>
            <link>https://medium.com/sausheong?source=rss----187e2cc596a4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:53:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/sausheong" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generative AI and copyright]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/sausheong/generative-ai-and-copyright-54f9c15e5f8c?source=rss----187e2cc596a4---4"><img src="https://cdn-images-1.medium.com/max/1536/1*yxSzcOgJBkLbtq8WjSXj1Q.png" width="1536"></a></p><p class="medium-feed-snippet">Exploring the legal complexities of generating content with AI</p><p class="medium-feed-link"><a href="https://medium.com/sausheong/generative-ai-and-copyright-54f9c15e5f8c?source=rss----187e2cc596a4---4">Continue reading on sausheong’s space »</a></p></div>]]></description>
            <link>https://medium.com/sausheong/generative-ai-and-copyright-54f9c15e5f8c?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/54f9c15e5f8c</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai-art]]></category>
            <category><![CDATA[copyright]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 00:35:59 GMT</pubDate>
            <atom:updated>2023-01-30T06:03:31.543Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Chatting about ChatGPT]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/sausheong/chatting-about-chatgpt-645783b72e6b?source=rss----187e2cc596a4---4"><img src="https://cdn-images-1.medium.com/max/1024/1*PSUfXKJLqLGgYflZC9v25Q.png" width="1024"></a></p><p class="medium-feed-snippet">Poking around at OpenAI&#x2019;s latest conversational AI</p><p class="medium-feed-link"><a href="https://medium.com/sausheong/chatting-about-chatgpt-645783b72e6b?source=rss----187e2cc596a4---4">Continue reading on sausheong’s space »</a></p></div>]]></description>
            <link>https://medium.com/sausheong/chatting-about-chatgpt-645783b72e6b?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/645783b72e6b</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 03:29:52 GMT</pubDate>
            <atom:updated>2022-12-07T13:22:02.046Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mystery of the Murdered Professor]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/sausheong/mystery-of-the-murdered-professor-d72ac102f7db?source=rss----187e2cc596a4---4"><img src="https://cdn-images-1.medium.com/max/1920/1*yFMhghRhxBenlCCzWaNSGw.jpeg" width="1920"></a></p><p class="medium-feed-snippet">A Programming Murder Mystery in Ruby</p><p class="medium-feed-link"><a href="https://medium.com/sausheong/mystery-of-the-murdered-professor-d72ac102f7db?source=rss----187e2cc596a4---4">Continue reading on sausheong’s space »</a></p></div>]]></description>
            <link>https://medium.com/sausheong/mystery-of-the-murdered-professor-d72ac102f7db?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d72ac102f7db</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[mystery]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 02:34:08 GMT</pubDate>
            <atom:updated>2021-03-16T14:47:59.179Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why it is difficult to accept the realities of a downturn]]></title>
            <link>https://medium.com/sausheong/why-it-is-difficult-to-accept-the-realities-of-a-downturn-f3fa70a45a23?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/f3fa70a45a23</guid>
            <category><![CDATA[slice-of-life]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[sociology]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sun, 29 Dec 2019 03:13:09 GMT</pubDate>
            <atom:updated>2019-12-29T14:02:49.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAqapDzJoxw9kXJY" /></figure><p>I bought a 17″ Sony Trinitron CRT monitor for $535 in 1999, one of my prized possessions that accompanied me during the few years which I hopped from rented room to rented room. It weighed almost 20kg and was a tremendous monster to lug around, maybe 20% of the total weight of my other stuff put together. I retired it (still working) when I got my Samsung 19″ LCD monitor ($220) about 2 years ago and my wife persuaded me to sell it off. However, I baulked when I was offered $50 by the <a href="http://en.wikipedia.org/wiki/Karung_guni">karung guni man</a>, after all, it was still working. So I refused to sell it.</p><p>The next time I mentioned it to a karung guni man, he wouldn’t even want to take it and wanted to charge me $5 to take it off my hands. Naturally I didn’t pay.</p><p>All these brought me to the couple of conversations I had with Winston and with Simon. Conversations that somehow drifted to talking about our lifestyles in the current state of the economy. Perhaps this was on my mind during our lunchtime chatter, since we talked about completely different things to begin with. Winston talked about how he struggled through his startup days to achieve where he is today. Simon and I talked about how people upgraded their lifestyles over the few good years before the current crisis, and having done so found it extremely hard to accept that they need to lower their expectations now. Stories of people who lost their jobs and cannot accept that their new jobs now pay 20% — 25% lower than their previous one. People who just bought their 42″ LCD TVs, high-end electronic gadgets, cars and even apartments, depended entirely on their salaries to pay for the installments and lost their jobs. People with shiny promising lives ahead of them during the prosperous times but now facing bleak, burgeoning loans and unable to come to terms with the new realities of a recession.</p><p>Which led me to think — what makes it so difficult for us to accept the realities of an <a href="http://en.wikipedia.org/wiki/Financial_crisis_of_2007%E2%80%932009">economic downturn</a>?</p><p>My guess is a combination of these three hypotheses:</p><h3><strong>Endowment effect</strong></h3><p>This simply means that people place a higher value on objects they own than objects that they do not. <a href="http://people.duke.edu/~dandan/webfiles/PapersPI/Value%20Buyer%20and%20Seller.pdf">An experiment conducted in Duke University by Ziv Carmon and Dan Ariely</a> showed how surprisingly irrational yet humanly plausible this is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nBfoV_omh-DSR6H2.jpeg" /><figcaption>Duke University’s Cameron Indoor Stadium</figcaption></figure><p>Duke University has a small basketball stadium which doesn’t have enough seats for all its fans so it designed an elaborate lottery system to allocate tickets instead. The experiment involved fans who has won tickets to an NCAA Final Four basketball tournament and fans who had not, 93 respondents in all. Each respondent was asked, one day prior to the match, to indicate their selling or buying price for a ticket to the match. The buying price question asked for the highest price he or she would pay for the ticket and the selling price question asked for the lowest price he or she would agree to sell. In addition, the would-be buyers would be asked to think of other items or experiences that would be equivalent in value to the tickets. The test was to find out how much the buyer value the experience as compared to an equivalent experience and how much the seller value losing that experience. In other words, it was an experiment to determine the existence of the endowment effect.</p><p>When the experiment ended, the 10% trimmed mean selling price was about $2,400 while the 10% trimmed mean buying price was about $170. That’s a difference by a factor of 14! Rationally speaking, the would-be buyer and the would-be seller should think of the experience in the same way since they were randomly picked fans. The only difference was that some of the respondents won a lottery for the ticket and others didn’t. It’s pretty hard to explain the differences between the selling price and the buying price but at the same time it is strangely familiar and human.</p><p>This is why it’s particularly bitter for us in this downturn — we have already owned our new lifestyle, and it has gained particularly high value. If we have not owned that brand new Honda Civic it wouldn’t have mattered so much, but now that we have it, losing it is much more painful, even though we had lived happily in the past without it.</p><h3><strong>Loss aversion</strong></h3><p>This again should be familiar to most of us. It refers to the tendency for people to prefer avoiding losses than to acquiring gains of similar value. For example, it is more painful to lose $1000 than it is pleasurable to gain $1000. Given a choice people would prefer the chance not to lose $1000 than the chance that they might gain $1000.</p><p>In a <a href="http://www.stat.columbia.edu/~gelman/surveys.course/TverskyKahneman1981.pdf">1981 paper by Amos Tversky and Daniel Kahneman,</a> researchers described an experiment conducted at the University of Stanford and the University of British Columbia where 2 groups of students (152 and 155 respectively) were asked to answer this brief questionnaire in a classroom setting:</p><blockquote><em>Imagine that the US is preparing for the outbreak of an unusual Asian disease, which is expected to kill 600 people. Two alternative programs to combat the disease have been proposed. Assume that the exact scientific estimate of the consequences of the programs are as follows:</em></blockquote><blockquote><em>If Program A is adopted, 200 people will be saved.</em></blockquote><blockquote><em>If Program B is adopted, there is a 1/3 probability that 600 people will be saved and 2/3 probability that no on will be saved.</em></blockquote><blockquote><em>Which of the two programs would you favor?</em></blockquote><p>As it turns out 72% of the respondents chose Program A and 28% chose Program B. However, when the questions were phrased like this:</p><blockquote><em>If Program C is adopted 400 people will die.</em></blockquote><blockquote><em>If Program D is adopted, there is a 1/3 probability that nobody will die and 2/3 probability that 600 people will die.</em></blockquote><blockquote><em>Which of the two programs would you favor?</em></blockquote><p>the reverse happens i.e. 78% of the respondents chose Program D and 22% chose Program C! As you can see Program A and C are essentially the same, as with Program B and D. The difference was how the questions were worded. Whereas Program A describes people being saved (a gain) while Program C describes people dying (a loss). Intuitively it seems right, but it is still pretty startling that mere words could affect us this way.</p><p>This helps to explain whey the idea that my monitor was worth so little is so repulsive that I’d rather believe that the karung guni man was short-changing me. If I had framed my thoughts in a different way, say comparing it with a tube of toothpaste, and it’s worth has been used up already, I wouldn’t be so hung up about selling it away.</p><h3><strong>Cognitive dissonance</strong></h3><p><a href="https://www.simplypsychology.org/cognitive-dissonance.html">Cognitive dissonance</a> is one of the most influential and extensively studied theories in social psychology. It is the uncomfortable feeling when we have two contradictory ideas at the same time. The theory is that in such situations we would be driven to change or justify our attitude or behavior. For example, if you believe that you are a careful driver and an accident happens, you would normally either blame it on the other driver or some external factor that doesn’t contradict with your self-belief that you’re a careful driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaX_-Vug33bBb_ijF-YyUA.png" /></figure><p>In this economic downturn, the self-belief that we are worth this much (in terms of salary or other compensation) contradicts with the reality that we have been offered a job that is paying less. The cognitive dissonance then drives us to angrily reject the offer as being unreasonable, the employer is trying to take advantage of the downturn or some other justification that doesn’t take away that self-belief.</p><h3><strong>So?</strong></h3><p>So what can we learn from this?</p><ul><li><em>Loss aversion</em> tells us that looking at it in a different perspective makes things less painful for us. It’s not losing a job, it’s galvanizing us to try out the other stuff we’ve always been too busy with.</li><li>What we learn from the <em>endowment effect</em> is that losing our stuff is painful. That will not go away. However we can make things less painful not only by spending only we can afford, but also spending a few levels less than what we can afford in order to buffer for this pain. I can afford that Honda Civic if I have my job and current salary, but shouldn’t I buy a cheaper car such that I can afford it even if I lose 50% of my salary?</li><li>Finally, <em>cognitive dissonance</em> is part of human nature but what we can’t change, we should adapt. Recognizing that our self-worth is not measured in terms of our salaries but other things our families and friends, that salaries and jobs, like most things in the world goes through cycles should give us better sanity in dealing with a rapidly changing economic crisis.</li></ul><p>Having knowledge of what makes is hurt so much in this downturn doesn’t really help us get back our jobs or salaries. But knowing that it is human to feel this way, and that everyone is feeling the same way probably helps us face it better.</p><p>I still have that 17″ Sony monitor lying somewhere. One of these days I will need to overcome the endowment effect and dump it.</p><p>[Update Dec 2019 — I have since given it away (for free) to another karung guni man who was collecting old CRT monitors.]</p><p><em>Originally published at </em><a href="https://blog.saush.com/2009/04/07/why-it-is-difficult-to-accept-the-realities-of-a-downturn/"><em>http://blog.saush.com</em></a><em> on April 6, 2009.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fa70a45a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sausheong/why-it-is-difficult-to-accept-the-realities-of-a-downturn-f3fa70a45a23">Why it is difficult to accept the realities of a downturn</a> was originally published in <a href="https://medium.com/sausheong">sausheong’s space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate MP3 waveforms with Ruby and R]]></title>
            <link>https://medium.com/sausheong/generate-mp3-waveforms-with-ruby-and-r-f6f3ac5697b3?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/f6f3ac5697b3</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[mp3]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sun, 29 Dec 2019 02:48:33 GMT</pubDate>
            <atom:updated>2019-12-29T02:54:07.777Z</atom:updated>
            <content:encoded><![CDATA[<p>I blame Rully for this. If it wasn’t for him I wouldn’t have been obsessed with this and spent a good few hours at night figuring it out last week. It all started when Rully mentioned that he knew how many beeps there are in the <a href="http://en.wikipedia.org/wiki/Mass_Rapid_Transit_(Singapore)">Singapore MRT</a> (subway system) <a href="https://github.com/sausheong/Wavform/blob/master/mrt_closing.mp3">‘doors closing’ warning</a>. There are 13 beeps, he explained and he said he found out by running a WAV recording of it through a <a href="http://en.wikipedia.org/wiki/MATLAB">MatLab</a> package which in turn generated a waveform that allowed him to count the number of beeps accurately (it is normally too fast for the ear to determine the number of beeps). Naturally such talk triggered the inner competitive geek in me. I happened to be doing Ruby and R integration at the moment (watch out for my talk at <a href="http://reddotrubyconf.com/">RedDotRubyConf</a> at the end of April) so I had no choice but to retrace his steps using my new toys. Really.</p><p><a href="http://en.wikipedia.org/wiki/Mp3">MP3</a> is a compressed and lossy audio encoding format and to generate a waveform I decided to convert it to WAV first. Doing this is relatively simple — there is a library called <a href="http://icanhasaudio.com/">icanhasaudio</a> that wraps around <a href="http://en.wikipedia.org/wiki/LAME">LAME</a> to encode and decode audio. Naturally you need to have LAME installed first in your machine before you can do this but once you have done that, decoding the MP3 is a breeze:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7695334b3fd58701339bebccf0a196c3/href">https://medium.com/media/7695334b3fd58701339bebccf0a196c3/href</a></iframe><p>That was easy enough. The next step was a bit trickier though. To understand how to create a waveform from a WAV file let’s digress a bit into what a WAV file is. <a href="http://en.wikipedia.org/wiki/WAV">WAV</a> is an audio file format, originally from IBM and Microsoft, used to store audio bitstreams.WAV is an extended <a href="http://en.wikipedia.org/wiki/Resource_Interchange_File_Format">RIFF</a> format, which is a little-endian version of the AIFF format (which is big-endian). In RIFF, data are stored in ‘chunks’ and for WAV, there are basically 2 types of chunks — a format chunk and a sound data chunk. The format chunk contains the parameters describing the waveform for example its sample rate, and the data chunk contains the actual waveform data. There are other chunks but because I’m really only interested in the waveform I’ll conveniently ignore them. This is how a minimal WAV file looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*GYMYR7eWXmZHdJFq" /></figure><p>The data chunk has a chunk ID which is always ‘data’, and a chunk size that is a long integer. Data in the data chunk is stored in sample points. A <strong>sample point</strong> is a value that represents a sample of a sound at a given moment in time. Each sample point is stored as a linear 2&#39;s-complement value from 9–32 bits wide, specificed in the BitsPerSample field in the format chunk. Sounds in a WAV file can also come in multiple channels (for e.g. a stereo sound will come in 2 channels, like our file.) For such multi-channel sounds, the sample points are interleaved, one from each channel. A grouping of sample points for a single point in time for all the channels is called a <strong>sample frame</strong>. This graphic explains it best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*33uZGJ5hOJ7CDQXP" /></figure><p>If you open the WAV up with a hex editor it will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*PElaioDwdsfc_Laa" /></figure><p>I wouldn’t go through the format chunks, in fact there is an easier way to find out the format, and that is for me to open up the WAV file using QuickTime and inspect it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*PpvIY6yStp5AB-VG" /></figure><p>For more information you can get the <a href="http://web.archive.org/web/20080113195252/http://www.borg.com/~jglatt/tech/wave.htm">WAV specs here</a>. This is the information we found of the WAV file that we will use in a while:</p><ul><li>Format : Linear PCM</li><li>Number of channels : 2</li><li>Number of bits per sample : 16</li></ul><p>In order to create the waveform, I opened up the WAV file, and collected each sample point from each channel and convert that sample point into an integer. This will be the data file I will use later in R to generate the waveform. Let’s take a look at the code now that we use to generate the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3011870eb4d2fcb550be3693b2cab3d8/href">https://medium.com/media/3011870eb4d2fcb550be3693b2cab3d8/href</a></iframe><p>Note that I didn’t read the number of channels from the WAV file but instead assumed it has 2 channels (stereo), to simplify the code. Firstly I open up the WAV file. I ignored the format chunk completely and looked for the data chunk only. Then I read the length of the data chunk by reading the next 4 bytes and unpacking it as a long integer (hence ‘l’ format in the String#unpack method). This gives me the length of the data chunk that I will need to read next.</p><p>Next, for ease of reading I wrap the returned data string in a StringIO object. As we found out earlier, each sample has 2 channels and each sample point has 16 bits, so we need to retrieve 32 bits or 4 bytes. Since each sample point has 16 bits, this means a short integer, so we unpack the 4 bytes that are read into 2 short integers, and this will give us the 2 sample points of 2 channels of that sample frame.</p><p>After that it’s a simple matter of stuffing the sample points into a CSV file.</p><p>Finally, to generate the waveform from the data file, I run it through a simple R script, which I integrated with Ruby using the <a href="https://github.com/clbustos/Rserve-Ruby-client">Ruby Rserve client</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f43548fbefd074b31e47b9f982c045d/href">https://medium.com/media/9f43548fbefd074b31e47b9f982c045d/href</a></iframe><p>The script generates the following PNG file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*8W2dnevRoUatfxW3" /></figure><p>As you can see from the waveform (ignoring the first 2 bulges, which are ‘doors’ and ‘closing’ respectively) there are 13 sharp pointy shapes, which represent a beep each.</p><p>You can get the code and images here from my <a href="https://github.com/sausheong/Wavform">GitHub repository</a>. If you’re interested to hear more about Ruby and R integration, do come down to the <a href="http://reddotrubyconf.com/">RedDotRubyConf</a> on 22 and 23 April 2011!</p><p><em>Originally published at </em><a href="https://blog.saush.com/2011/03/24/generate-mp3-waveforms-with-ruby-and-r/"><em>http://blog.saush.com</em></a><em> on March 24, 2011.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f3ac5697b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sausheong/generate-mp3-waveforms-with-ruby-and-r-f6f3ac5697b3">Generate MP3 waveforms with Ruby and R</a> was originally published in <a href="https://medium.com/sausheong">sausheong’s space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create 3D anaglyph images with 3 lines of Ruby code]]></title>
            <link>https://medium.com/sausheong/create-3d-anaglyph-images-with-3-lines-of-ruby-code-4e9e063dca77?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4e9e063dca77</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 13:29:23 GMT</pubDate>
            <atom:updated>2019-12-28T15:10:06.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBx5NJOzziQSOZsMOKe4Tw.png" /><figcaption>Red-blue 3D glasses</figcaption></figure><p>3D has always fascinated me. When I was young my brother and I had a <a href="http://en.wikipedia.org/wiki/View-Master">ViewMaster</a> and a <a href="http://www.viewmaster.co.uk/htm/panpet.asp">Pan-Pet Panorama Stereo Viewer</a>, both of which totally bowled us over when we first saw it. My brother as usual totally took it apart and fixed it up again, multiple times while I simply spent hours goggling at the thing. I have no idea where they are now but thinking back they were my first recollection of understanding stereoscopy is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*BBP76cPYEIfngyuA02gw-w.png" /><figcaption><em>ViewMaster</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*W6U6gpoQlm50fuq8SwFwyA.png" /><figcaption><em>Pan-Pet Panorama Stereo Viewer</em></figcaption></figure><h3>A bit of history</h3><p>It’s probably surprising to most people (at least it was to me) that the modern techniques of 3D imaging and stereoscopy dated way back before even photography. In fact the first few stereoscopic images were drawings. The picture below shows one of the earliest stereoscopic drawings by <a href="http://www.virtualuffizi.com/biography/Jacopo-Chimenti-called-Empoli.htm">Jacopo Chimenti</a>, a painter from Florence, Italy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*gZgEiLqugNFCiF_v5WUrDw.png" /><figcaption><em>Jacopo Chimenti’s first stereoscopic image</em></figcaption></figure><p>In 1838, <a href="http://en.wikipedia.org/wiki/Charles_Wheatstone">Charles Wheatstone</a>, a British inventor, published a paper that provided the scientific basis for stereography. He showed that the brain unifies the slightly different two-dimensional images from each eye into a single object of three dimensions. Wheatstone’s early stereographs were also drawings rather than photographs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*NHXmZHdkKlF2ofdUTtAxlQ.png" /><figcaption><em>Wheatstone’s stereoscope</em></figcaption></figure><p>Photographic stereographs were first produced in 1849 by the English physicist <a href="http://en.wikipedia.org/wiki/David_Brewster">David Brewster</a> who improved the stereoscope and in 1849 the first true stereo camera with two lenses.</p><h3>3D/stereographic imaging techniques</h3><p>The principles of stereoscopy are quite simple. We see things in 3 dimensions (i.e. being able to see 3-dimensional depth) because each of our 2 eyes actually see a slightly different image. This is because our eyes positioned are apart from each other which generates what is called binocular disparity. Recreating this effect with a 2-dimensional image then allows us to ‘see’ the image in 3D.</p><p>There are a number of ways to do this but generally the principle revolves around creating a set of 2 images, one for each eye and ‘forcing’ the left eye to view the left image and the right eye to view the right image.</p><h4>Freeviewing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*E-roX0xSFR53I209T7kuDQ.png" /><figcaption><em>Stereogram with cross-eyed method</em></figcaption></figure><p>This method places the left image on the right side and the right image on the left side. To view the image in stereo, force your eyes to go cross-eyed, which will produce 3 images. Then slowly ease the eyes to view the middle image in 3D. This is not as silly as it sounds, and actually works though it can be a strain on the eyes (obviously).</p><h4>Wiggle method</h4><p>The wiggle method surprises a lot of people (including me when I first read about it) but it can sometimes be pretty effective. Basically you use the 2 images and create a GIF that alternates between each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*D6L7G25SIeEIVMtUtNT5NA.png" /><figcaption><em>Stereogram with wiggle method</em></figcaption></figure><h4>Viewers</h4><p>This method uses various kinds of viewers, from the 18th century Wheatstone stereoscope to the popular <a href="http://xroads.virginia.edu/~MA03/staples/stereo/stereographs.html">Holmes American stereoscope</a> and the transparency viewers like the ViewMaster and the Pan-Pet that I grew up with. It also includes high tech head-mounted displays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*FO5DKNRrIx1vQKiZ0_aa-g.png" /><figcaption><em>Holmes’ American Stereoscope (reproduction)</em></figcaption></figure><h4>Parallax barrier and lenticular printing</h4><p>These 2 methods are similar though parallax barrier is pretty high-tech while lenticular prints is as low-tech as it can be. <a href="http://electronics.howstuffworks.com/nintendo-3ds5.htm">Parallax barrier</a> essentially places a barrier in front of an image source, usually a LCD display, with a series of precision slits, allowing each eye to see a different set of pixels. This is famously used in the <a href="http://www.nintendo.com/3ds/hardware">Nintendo 3DS</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZkV-rHimzfy-ADJ-z6TJQ.png" /><figcaption>Nintendo 3DS</figcaption></figure><p><a href="http://en.wikipedia.org/wiki/Lenticular_printing">Lenticular printing</a> uses a similar technique but with lenticular lenses. Lenticular prints are popular as novelty items and you’d probably encountered them in many places without knowing what it was called.</p><p>These 2 methods are often also classified as ‘autostereoscopy’ or glasses-free 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*Uy0Z53YIx1p-bYHhmJmjFA.png" /><figcaption><em>Difference between parallax barrier and lenticular printing</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*ziN9i1fm1t6p9m6F1bJj2w.png" /><figcaption><em>Lenticular print of a promotion item</em></figcaption></figure><h4>3D glasses</h4><p>This is probably the method you’re most likely to encounter nowadays in movies and in 3D TVs. I classify both passive and active glasses in this category though the actual technologies can be vastly different such as alternating different frames with special projectors and using polarized light.</p><p>Which brings us to the type of 3D image we’ll be trying out today — <a href="http://en.wikipedia.org/wiki/Anaglyph_image">anaglyphs</a>.</p><p>The idea of anaglyphs is simple. We start with the 2 left and right images again. This time they are superimposed on each other, but the left would be corrected to show only red color while the right would be corrected to show cyan color. Actually we can use other colors besides red and cyan but these 2 colors are the most popular (and patent-free).</p><p>The image is then viewed with a pair of glasses that filter soff red on the left lens and cyan on the right lens. The results is that the left eye would only see the left image and the right eye the right image, therefore generating the perception of depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*sBZm62TWwlFJWcLFO3hyww.png" /><figcaption><em>Red-cyan anaglyph glasses</em></figcaption></figure><p>The main problem with this technique (besides the necessity of wearing glasses) is that the colors are a bit wonky. Also if some color from the left image gets into the right eye (and vice versa) a faintly colored “ghost” will be seen. And if the filter from each lens filters off different amount of light resulting in luminance imbalance, it can easily cause headaches (happened to me lots of times during the experiments I did below).</p><p>However there are plenty of advantages of anaglyphs. Firstly there isn’t a need for fancy high-tech equipment. Anaglyph red-cyan glasses can be easily created at home or bought cheaply and as you will see below, creating anaglyphs is child’s play.</p><h3>Creating anaglyphs with Ruby</h3><p>Creating anaglyphs is ridiculously easy with <a href="http://rmagick.rubyforge.org/">RMagick</a>. This is the whole script I used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2553cd3970465162babbf81725470f64/href">https://medium.com/media/2553cd3970465162babbf81725470f64/href</a></iframe><p>As you can see, the real work is done in only 3 lines of code. Firstly I create an ImageList object (assuming the first parameter is the file name of the first image). Then I use #gamma_correct and filter off the greens and blues of the left image while keeping the reds. The for the right image, I do the same thing, except this time I filter off the reds while keeping the greens and blues. Finally I use #composite and blend the 2 images together using the <a href="http://en.wikipedia.org/wiki/Blend_modes">screen blending mode</a> (which lightens the image after blending). I used CenterGravity to place the right image at the center of the left image here but it really doesn’t matter since both images are supposed to be the same size anyway. And what remains is just to write the anaglyph back into a file.</p><p>Of course, all of these means nothing if we can’t capture the left and right images. For this there are the stereo cameras, ranging from the amazing to the weird and the totally slap-together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*HJUstZdVudbMkygUqhBPfA.png" /><figcaption><em>3D World 120 Tr-Lens: Stereoscopic Three Lenses 3D Camera</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*AcZgnRyTXThlLTfRzsTorw.png" /><figcaption><em>Fujifilm FinePix REAL 3D W3</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*q_xWChisEES8r-7LwAXCUQ.png" /><figcaption><em>2 instant cameras as conjoined stereo camera</em></figcaption></figure><p>Alternatively you can do the same thing with a single camera, although I wouldn’t recommend it for anything else except still shots. To do this, some recommend to use what is known as the <a href="http://nzphoto.tripod.com/3d/010chacha.html">‘cha-cha’ technique</a>. This requires the photographer to snap a picture then shifting weight slightly to the left or right therefore moving a few centimeters to take a reasonably good second image.</p><p>Me? I didn’t want to buy a fancy 3D camera and wasn’t inclined do the cha-cha so I applied a bit of <a href="http://www.macgyveronline.com/pages/macgyverisms.html">MacGyverism</a> on my primary camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*6pY5XBCjPrx7_b3EwsRp6A.png" /><figcaption><em>MacGyver’ed dual iPhones with rubber-bands</em></figcaption></figure><p>It’s not perfect but it does take a reasonably good picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*773xgMgF7omf5BEwAC0L0w.png" /><figcaption><em>Left image of Kai Wen</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*hiZkZSDz65uSxtOwHotxug.png" /><figcaption><em>Right image of Kai Wen</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BRmpe_6iXjc2qgC7N16jRQ.png" /><figcaption><em>Anaglyphic image of Kai Wen</em></figcaption></figure><p><em>Originally published at </em><a href="https://blog.saush.com/2011/07/19/create-3d-anaglyph-images-with-3-lines-of-ruby-code/"><em>http://blog.saush.com</em></a><em> on July 19, 2011.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9e063dca77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sausheong/create-3d-anaglyph-images-with-3-lines-of-ruby-code-4e9e063dca77">Create 3D anaglyph images with 3 lines of Ruby code</a> was originally published in <a href="https://medium.com/sausheong">sausheong’s space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a photo mosaic web app in Go]]></title>
            <link>https://medium.com/sausheong/creating-a-photo-mosaic-web-app-in-go-887c8c502f82?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/887c8c502f82</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 13:13:38 GMT</pubDate>
            <atom:updated>2019-12-28T13:13:38.089Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, my good friend <a href="https://twitter.com/indianguru">Satish Talim</a> had this great idea to create a series of Go challenges to help Go programmers to up their game. The idea was to create a programming problem every month (or so) that presents a fresh and interesting challenge to the Go community. There would be prizes to win, but more importantly, it was a community effort to help each other to improve ourselves. Satish asked me to write a challenge, and I readily agreed to create <a href="http://golang-challenge.com/go-challenge3/">challenge #3</a>.</p><p>Being a web application programmer for most of my career, it was the most natural thing to do to create a challenge that’s based on creating a web application. And some time back, <a href="https://developer.yahoo.com/blogs/ydn/creating-photo-mosaics-yahoo-boss-image-search-7453.html">I wrote a mosaic-generating script using Ruby during a hackathon</a>, so I thought to marry both ideas together to create a challenge to create photo mosaic web app.</p><p>To be honest, at the time of issuing the challenge I haven’t actually written the photo mosaic web app yet. In fact, I only started writing it after the challenge was over. It took me the better part of 2 days to complete the photo mosaic web app. But I wasn’t finished yet, and I wanted to go a bit further and use Go’s concurrency to improve its performance. This blog post is the results of what I did.</p><p>The code for this blog post is found at <a href="https://github.com/sausheong/mosaic">https://github.com/sausheong/mosaic</a>. Note that the code in GitHub has slight variations from the code described below.</p><p>The live site is found at <a href="http://mosaic.saush.com/">http://mosaic.saush.com</a>. It is deployed using <a href="https://www.docker.com/">Docker</a> to Digital Ocean, through <a href="https://www.tutum.co/">Tutum</a>. The performance on the live site is not as good as described here, as it is only running on 1 CPU VM with 512MB.</p><p><em>[Update 28 Dec 2019: The live site is no longer available. </em><a href="https://techcrunch.com/2015/10/21/docker-acquires-cloud-startup-tutum-for-container-shipping-and-management/"><em>Tutum was bought by Docker</em></a><em>.]</em></p><h3>Creating the photo mosaic</h3><p>A photographic mosaic, or a photo mosaic is a picture (usually a photograph) that has been divided into (usually equal sized) rectangular sections, each of which is replaced with another picture (called a tile picture). If we view it from far away or if you squint at it, then the original picture can be seen. If we look closer though, we will see that the picture is in fact made up of many hundreds or thousands of smaller tile pictures.</p><p>The basic idea is simple — the web application allows a user to upload a target picture, which will be used to create a photo mosaic. To make things simple, I will assume that tile pictures are already available and are correctly sized.</p><p>Let’s start with the photo mosaic algorithm. The steps are simple and the whole web application can be written without the use of any third-party libraries.</p><ol><li>Build up a tile database, hash of tile pictures, by scanning a directory of pictures, then using the file name as the key and the average color of the picture as the value. The average color is a 3-tuple calculated from getting the red, green and blue (RGB) of every pixel and adding up all the reds, greens and blues, then divided by the total number of pixels</li><li>Cut the target picture into smaller pictures of the correct tile size</li><li>For every tile-sized piece of the target picture, assume the average color to the the color of the top left pixel of that piece</li><li>Find the corresponding tile in the tile database that is the nearest match to the average color of the piece of the target picture, and place that tile in the corresponding position in the photo mosaic. To find the nearest match, we calculate the Euclidean distance between the two color 3-tuples by converting each color 3-tuple into a point in a 3-dimensional space</li><li>Remove the tile from the tile database so that each tile in the photo mosaic is unique</li></ol><p>I placed all the mosaic creating code in a single source file named mosaic.go. Let’s look at each function in this file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddd7303c1b85009be8e4f907fcde304c/href">https://medium.com/media/ddd7303c1b85009be8e4f907fcde304c/href</a></iframe><p>First is the averageColor function, which takes the red, green and blue of each pixel in the image, adds up all the reds, greens and blues and then divides each sum by the total number of pixels in the image. Then we create a 3-tuple (actually a 3 element array) consisting of these numbers.<br> Next, we have the resize function. The resize function resizes an image to a new width.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49b29987cbd9a50a4e8e07e2ae3fda5f/href">https://medium.com/media/49b29987cbd9a50a4e8e07e2ae3fda5f/href</a></iframe><p>The tileDB function creates a database of the tile picture by scanning the directory where the tile pictures are located.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b34273c9d5ae8e5a06f3f7d7834ca25a/href">https://medium.com/media/b34273c9d5ae8e5a06f3f7d7834ca25a/href</a></iframe><p>The tile database is a map with a string as the key a 3-tuple (in this case a 3-element array) as the value. I open up each image file in the directory and then get the average color of the image to create an entry in the map. The tile database is used to find the correct tile picture in the tile picture directory. It is passed into the nearest function, along with the target color 3-tuple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e959f99e4e06aeb1fdb34c4fb9b6f31/href">https://medium.com/media/9e959f99e4e06aeb1fdb34c4fb9b6f31/href</a></iframe><p>Each entry in the tile database is compared with the target color and the entry with the smallest distance is returned as the nearest tile, and also removed from the tile database. The distance function calculates the Euclidean distance between two 3-tuples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d95ba0a3ec3086573ddfcc7f1bf5e553/href">https://medium.com/media/d95ba0a3ec3086573ddfcc7f1bf5e553/href</a></iframe><p>Finally, scanning and loading the tile database every time a photo mosaic is created can be pretty cumbersome. I want to do that only once, and clone the tile database every time a photo mosaic is created. The source tile database, TILEDB is then created as a global variable and populated on the start of the web application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d604c5e40e3f60b5ec61cf92794d132/href">https://medium.com/media/6d604c5e40e3f60b5ec61cf92794d132/href</a></iframe><h3>The photo mosaic web application</h3><p>With the mosaic-generating functions in place, I can start writing my web application. The web application is placed in a source code file named main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e2e0078ad91cc29a4dc0c3d37cc0918/href">https://medium.com/media/2e2e0078ad91cc29a4dc0c3d37cc0918/href</a></iframe><p>The main logic for creating the photo mosaic is in the mosaic function, which is a handler function. First, I get the uploaded file and also the tile size from the form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94eedb1aba1a1be62962f5d78d92606f/href">https://medium.com/media/94eedb1aba1a1be62962f5d78d92606f/href</a></iframe><p>Next, I decode the uploaded target image, and also create a new photo mosaic image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6df09cae11675756d064cd549a286524/href">https://medium.com/media/6df09cae11675756d064cd549a286524/href</a></iframe><p>I also clone the source tile database, and set up the source point for each tile (this is needed by the image/draw package later).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2917c3ad507d43643f2b52e5707dd59/href">https://medium.com/media/b2917c3ad507d43643f2b52e5707dd59/href</a></iframe><p>I am now ready to iterate through each tile-sized piece of the target image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5b072e2cfa3653074b3773991ff676/href">https://medium.com/media/0c5b072e2cfa3653074b3773991ff676/href</a></iframe><p>For every piece, I pick the top left pixel and assume that’s the average color. Then I find the nearest tile in the tile database that matches this color. The tile database gives me a filename, so I open up the tile picture, and resize it to the tile size. The resultant tile is drawn into the photo mosaic I created earlier.</p><p>Once the photo mosaic is created, I encode it into JPEG format, then encode it once again into a base64 string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6198104293b99499e1e7bb773ff532f1/href">https://medium.com/media/6198104293b99499e1e7bb773ff532f1/href</a></iframe><p>The original target picture and the photo mosaic are then sent to the results.html template to be displayed on the next page. As you can see, the image is displayed with using a data URL with the base64 content that is embedded in the web page itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b83028c9b80ac272fc8d2772966073c/href">https://medium.com/media/1b83028c9b80ac272fc8d2772966073c/href</a></iframe><p>Here’s a screenshot of the mosaic that’s created.</p><p>Now that we have the basic mosaic generating web application, let’s create the concurrent version of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xGDvxYncycP7rwx9VERwrg.png" /><figcaption><em>Basic photo mosaic web app</em></figcaption></figure><h3>Concurrent photo mosaic web application</h3><p>One of the more frequent use of concurrency is to improve performance. The web application I just showed created a mosaic from a 151KB JPEG image in about 2.25 seconds. The performance is not really fantastic and can definitely be improved using some concurrency. The algorithm I am using in this example to build some concurrency into the photo mosaic web application is quite straightforward.</p><ol><li>Split the original image into 4 quarters</li><li>Process them at the same time</li><li>Combine the results back into a single mosaic</li></ol><p>From a diagrammatic point of view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cLDCTUXdd4eOK3CRVxioSA.png" /><figcaption><em>Concurrency algorithm</em></figcaption></figure><p>A word of caution — this is not the only way that performance can be improved or concurrency can be achieved, but only one relatively simple and straightforward way.</p><p>The only function that changes in this is the mosaic handler function. In the earlier program, I had a single handler function that created the photo mosaic. In the concurrent version of the photo mosaic web application, I need to break up that function into two separate functions, called cut and combine respectively. Both the cut and the combine functions are called from the mosaic handler function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60c077df97befb0512dffe9d4491c945/href">https://medium.com/media/60c077df97befb0512dffe9d4491c945/href</a></iframe><p>Cutting up the image is handled by the cut function, in what is known as the fan-out pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*DgJ-UpTo4NyKUa0Be75c1g.png" /><figcaption><em>Splitting the target picture into 4 quadrants</em></figcaption></figure><p>The original image is cut up into 4 quadrants to be processed separately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d88d0052daf0126835fed7b7c06f25a/href">https://medium.com/media/7d88d0052daf0126835fed7b7c06f25a/href</a></iframe><p>You might notice that these are regular functions and not goroutines, how can they run concurrently? The answer is because the cut function creates an anonymous goroutine and returns a channel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51115e985ec53c83eb5da87b25c6e89f/href">https://medium.com/media/51115e985ec53c83eb5da87b25c6e89f/href</a></iframe><p>The logic is exactly the same as in the original photo mosaic web application. I created a channel in the cut function and started up an anonymous goroutine that sends the results to this channel, then return the channel. This way, the channel is immediately returned to the mosaic handler function, and the completed photo mosaic segment is sent to the channel when the processing is done. You might notice that while I’ve created the return channel as a bi-directional channel, I can typecast it to be returned as a receive-only channel.</p><p>I’ve cut the original image into 4 separate pieces and convert each piece into a part of a photo mosaic. It’s time to put them together again, using what is commonly known as the fan-in pattern, in the combine function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec09b55d258897f08c7b1f138029783b/href">https://medium.com/media/ec09b55d258897f08c7b1f138029783b/href</a></iframe><p>As in the cut function, the main logic in combining the images are in an anonymous goroutine, and I create and return a receive-only channel. As a result, I can encode the original image while combining the 4 photo mosaic segments.</p><p>In the anonymous goroutine, I create another anonymous function and assign it to a variable copy. This function copies a photo mosaic segment into the final photo mosaic and will be run as a goroutine later. Because the copy function is called as a goroutine, I will not be able to control when they complete. To synchronize the completion of the copying, I use a WaitGroup. I create a WaitGroup wg, then set the counter to 4 using the Add method. Each time the copy function completes, it will decrement the counter using the Done method. I call the Wait method just before encoding the image to allow all the copy goroutines to complete and I actually have a complete photo mosaic image.</p><p>Remember that the input to the combine function includes the 4 channels coming from the cut function containing the photo mosaic segments, and I don’t know when the channels actually have segments. I could try to receive each one of those channels in sequence, but that wouldn’t be very concurrent. What I would like to do is to start processing whichever segment that comes first and the select statement fits the bill nicely.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/467ac947184bbebb2ce7752f4e0de8aa/href">https://medium.com/media/467ac947184bbebb2ce7752f4e0de8aa/href</a></iframe><p>I loop indefinitely and in each iteration, I select the channel that is ready with a value (or if more than one is available, Go randomly assigns me one). I use the image from this channel and start a goroutine with the copy function. Note that I’m using the multi-value format for receiving values from the channel, meaning the second variable (ok1, ok2, ok3 or ok4) tells me if I have successfully received from the channel. The for loop breaks once I have received successfully on all channels.</p><p>Moving on, and referring to the WaitGroup wg I used earlier, remember that even though I received all the photo mosaic segments successfully, I have in turn started 4 separate goroutines, which might not have completed at that point in time. The Wait method on the WaitGroup wg blocks the encoding of the assembled photo mosaic until the photo mosaic is completed.</p><p>Here’s a screenshot of the results, using the same target picture and tile pictures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*x6zqG0X3XOqyCTbSNeBDqg.png" /><figcaption><em>Photo mosaic web application with concurrency</em></figcaption></figure><p>If you’re sharp-eyed, you might see the slight differences in the photo mosaic that’s generated. The final photo mosaic is assembled from 4 separate pieces and the algorithm doesn’t smoothen out the rough edges. However, you can see the difference in performance — where the basic photo mosaic web application took 2.25 seconds, this one using concurrency only takes almost a quarter of that time, around 646 miliseconds.</p><p>For readers who are really observant you might realize that both web applications are actually running on just one CPU! <a href="http://blog.golang.org/concurrency-is-not-parallelism">As mentioned by Rob Pike, concurrency is not parallelism</a> — what I’ve shown you is how we can take a simple algorithm and break it down into a concurrent one, with no parallelism involved! None of the goroutines are actually running in parallel (since there is only one CPU) even though they are running independently.<br> Of course it would be cruel not to go the last step and show how it actually runs using multiple CPUs. To do this, I simply need to set the GOMAXPROCS in the runtime to the actual number of CPUs running on my system. The changes are in the main.go file. Remember to import the runtime package before making the change below.</p><p><em>[Update 28 Dec 2019: GOMAXPROCS setting defaulted to 1 prior to Go 1.5, as of Go 1.5, the default is whatever the OS detects to be the number of CPUs at the start of the program, so this next step is really unnecessary, you will be using all the CPUs by default].</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cc7bd9e5f27f5195d4f0e8f9d034947/href">https://medium.com/media/1cc7bd9e5f27f5195d4f0e8f9d034947/href</a></iframe><p>I compile and then upload the same target picture again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yJ7U2d1OTQn7rVSWylb04g.png" /><figcaption><em>Photo mosaic web application with concurrency and 8 CPUs</em></figcaption></figure><p>As you can see, the performance has improved 3 times, from 646 milliseconds to 216 milliseconds! And if we compare that with our original photo mosaic web application with 2.25 seconds, that’s a 10 times performance improvement! That is an actual comparison, even though we did not run it with 8 CPUs previously, our original photo mosaic web application is not concurrent and therefore can only use one CPU — giving it 8 CPUs make no difference at all.<br> What is also interesting to note is that there is no difference between the original and the concurrent web applications, in terms of the photo mosaic algorithm. In fact, between the two applications, the mosaic.go source file was not modified at all. The only difference is concurrency, and that is a testament to how powerful it is.</p><p><em>Originally published at </em><a href="https://blog.saush.com/2015/06/24/creating-a-photo-mosaic-web-app/"><em>http://blog.saush.com</em></a><em> on June 23, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=887c8c502f82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sausheong/creating-a-photo-mosaic-web-app-in-go-887c8c502f82">Creating a photo mosaic web app in Go</a> was originally published in <a href="https://medium.com/sausheong">sausheong’s space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a simple cross-platform desktop game with Go]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/sausheong/create-a-simple-cross-platform-desktop-game-with-go-8e5432128c9b?source=rss----187e2cc596a4---4"><img src="https://cdn-images-1.medium.com/max/600/0*gzQS5cC4OVRHWMpd.jpg" width="600"></a></p><p class="medium-feed-snippet">A few months ago I fiddled around with writing Space Invaders using Go. I had a lot of fun writing it but the output only worked on iTerm2&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/sausheong/create-a-simple-cross-platform-desktop-game-with-go-8e5432128c9b?source=rss----187e2cc596a4---4">Continue reading on sausheong’s space »</a></p></div>]]></description>
            <link>https://medium.com/sausheong/create-a-simple-cross-platform-desktop-game-with-go-8e5432128c9b?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e5432128c9b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 07:26:10 GMT</pubDate>
            <atom:updated>2019-12-28T08:01:52.027Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Setting up a Raspberry Pi 4 as an development machine for your iPad Pro]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/sausheong/setting-up-a-raspberry-pi-4-as-an-development-machine-for-your-ipad-pro-3813f872fccc?source=rss----187e2cc596a4---4"><img src="https://cdn-images-1.medium.com/max/2600/1*6hylsqrhm_tpaiPIuH8tBg.jpeg" width="4032"></a></p><p class="medium-feed-snippet">Years ago when I was just starting out in my career, a couple of friends and I came together with a new startup idea. The plan was to take&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/sausheong/setting-up-a-raspberry-pi-4-as-an-development-machine-for-your-ipad-pro-3813f872fccc?source=rss----187e2cc596a4---4">Continue reading on sausheong’s space »</a></p></div>]]></description>
            <link>https://medium.com/sausheong/setting-up-a-raspberry-pi-4-as-an-development-machine-for-your-ipad-pro-3813f872fccc?source=rss----187e2cc596a4---4</link>
            <guid isPermaLink="false">https://medium.com/p/3813f872fccc</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[ipad-pro]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Sau Sheong]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 06:58:49 GMT</pubDate>
            <atom:updated>2019-12-26T19:45:13.882Z</atom:updated>
        </item>
    </channel>
</rss>