<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Soulwire &#187; Algorithm</title>
	<atom:link href="http://blog.soulwire.co.uk/tag/algorithm/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.soulwire.co.uk</link>
	<description>Art + Technology</description>
	<lastBuildDate>Mon, 21 Mar 2011 22:27:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>What The Fuck Is My Mashup?</title>
		<link>http://blog.soulwire.co.uk/laboratory/javascript/what-the-fuck-is-my-mashup</link>
		<comments>http://blog.soulwire.co.uk/laboratory/javascript/what-the-fuck-is-my-mashup#comments</comments>
		<pubDate>Mon, 07 Feb 2011 16:56:46 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Miscellany]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=1279</guid>
		<description><![CDATA[The fruits of a Sunday hangover; What The Fuck Is My Mashup? is an idea generator for ridiculous (but sometimes plausible) mashups. Inspired by What The Fuck Should I Make For Dinner by Zach Golden, WTFIMM is a simple JavaScript based randomiser that takes a series of templates and a corpus of words and turns [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/javascript/springboard-javascript-css-html-template' rel='bookmark' title='Permanent Link: Introducing Springboard'>Introducing Springboard</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator' rel='bookmark' title='Permanent Link: Smack My Glitch Up'>Smack My Glitch Up</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.soulwire.co.uk/wp-content/uploads/2011/02/wtfimm.jpg" alt="What The Fuck Is My Mashup" title="What The Fuck Is My Mashup" width="710" height="360" /></p>
<p>The fruits of a Sunday hangover; <a href="http://whatthefuckismymashup.com/"  title="What The Fuck Is My Mashup" target="_blank">What The Fuck Is My Mashup?</a> is an idea generator for ridiculous (but sometimes plausible) <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://en.wikipedia.org/wiki/Mashup_(web_application_hybrid)"  target="_blank">mashups</a>.<span id="more-1279"></span></p>
<p>Inspired by <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.whatthefuckshouldimakefordinner.com/" >What The Fuck Should I Make For Dinner</a> by <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.zachgolden.com/"  target="_blank">Zach Golden</a>, <strong>WTFIMM</strong> is a simple JavaScript based randomiser that takes a series of templates and a corpus of words and turns them into concepts that utilise the latest technologies, APIs and social media platforms.</p>
<p>I&#8217;ve abstracted the code into a simple framework which I&#8217;ve called the <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/https://github.com/soulwire/WTFEngine"  target="_blank">WTF Engine</a>, that allows you to create a generator for any subject.</p>
<p>Here are a few of my favourite generative mashups so far:</p>
<ul>
<li>Blackberry application that generates poetry based on Yelp data</li>
<li>Platform for building Wii controlled, memcached dashboard widgets for Open Frameworks enabled devices</li>
<li>Windows optimised GMail configurator for social microblogging</li>
<li>Podcast that generates poetry based on Google Earth data</li>
<li>Scalable, PHP based Feedburner API explorer with a hand tracking front-end</li>
<li>Feature detecting blogging platform for Lingo, Haxe and AS3</li>
<li>Pascal based kiosk to replace data visualisations and hook into GMail via Twitter and Google Maps</li>
<li>Multi-touch, open source Digg microblogging utility powered by Slashdot and the Google Gears C# API</li>
<li>Platform for building dynamic, Wii controlled iPad applications for MATLAB enabled devices</li>
<li>Python based Del.icio.us and GitHub mashup, designed for generative gaming</li>
<li>Objective C interpreter for creating dynamic microblogging experiences in JavaScript</li>
<li>Scalable, Wii controlled GitHub shopping utility powered by Foursquare &#038; the Yahoo Pipes API</li>
<li>Ajax based platform for rapidly developing kiosks based on Google Gears data</li>
<li>Perl based platform for rapidly developing art installations based on GitHub data</li>
</ul>
<p>The <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/https://github.com/soulwire/WTFEngine"  target="_blank">WTF Engine code</a> and this particular implementation is available in my <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/https://github.com/soulwire"  target="_blank">GitHub repository</a>.</p>
<p>Have fun, and if for any bizarre reason you make one of them, let me know!</p>
<p><a href="http://whatthefuckismymashup.com/"  target="_blank" title="What The Fuck Is My Mashup">http://whatthefuckismymashup.com/</a></p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/javascript/springboard-javascript-css-html-template' rel='bookmark' title='Permanent Link: Introducing Springboard'>Introducing Springboard</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator' rel='bookmark' title='Permanent Link: Smack My Glitch Up'>Smack My Glitch Up</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/javascript/what-the-fuck-is-my-mashup/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Recursive Polygon Subdivision</title>
		<link>http://blog.soulwire.co.uk/laboratory/flash/recursive-polygon-subdivision</link>
		<comments>http://blog.soulwire.co.uk/laboratory/flash/recursive-polygon-subdivision#comments</comments>
		<pubDate>Thu, 27 May 2010 12:51:48 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=1131</guid>
		<description><![CDATA[This is a little algorithm I sketched in my moleskin on the train and for once had the free time to build. The idea is to split a convex polygon between two line segments, creating two new polygons. Each shape is pushed into a queue ready to be subdivided itself. Despite the simplicity of the [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/05/SD001.swf"  rel="lightbox;width=900;height=650;" ><img src="http://blog.soulwire.co.uk/wp-content/uploads/2010/05/SD001_001.jpg" alt="Recursive Subdivision" title="Recursive Subdivision" width="710" height="360" class="alignnone size-medium wp-image-1134" /></a></p>
<p>This is a little algorithm I sketched in my <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.moleskine.co.uk/products/"  target="_blank">moleskin</a> on the train and for once had the free time to build. The idea is to split a convex polygon between two line segments, creating two new polygons. Each shape is pushed into a queue ready to be subdivided itself. Despite the simplicity of the algorithm, the results are quite nice and with certain configurations often far removed from what I would have expected &#8211; surprise is always good.<span id="more-1131"></span></p>
<h3>The Subdivide Algorithm</h3>
<p>Here are the basic steps used to create the <a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/05/SD001.swf"  rel="lightbox;width=900;height=650;" >sketch</a> above:</p>
<ul>
<li>Create the first polygon</li>
<li>Pick two adjacent vertices at random</li>
<li>Use linear interpolation to find a point between them <em>(P1)</em></li>
<li>You now have a point on one line segment connecting the two vertices</li>
<li>Choose another line segment from the polygon</li>
<li>Find a point along this line segment <em>(P2)</em></li>
<li>Build a new polygon by moving clockwise from <em>P1</em> to <em>P2</em></li>
<li>Build a second polygon by moving clockwise from <em>P2</em> back to <em>P1</em></li>
<li>Splice the original polygon from the list and insert the two new ones</li>
<li>Choose a polygon from the list and <em>(&uarr;repeat)</em></li>
</ul>
<p>Very simple, but you can start to have fun with each of these steps to produce different results. Here are some of the variations which can be created with the <a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/05/SD001.swf"  rel="lightbox;width=900;height=650;" >demo</a>.</p>
<ul>
<li>Choose line segments to cut at random</li>
<li>Always subdivide between the two longest line segments</li>
<li>Always interpolate (choose points) half way along segments</li>
<li>Choose points at random positions along line segments</li>
<li>Only mark some polygons eligible for subdivision</li>
<li>Vary the minimum area of divisible polygons</li>
</ul>
<h3>Source Code</h3>
<p>The <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://code.google.com/p/soulwire/source/browse/trunk/projects/Subdivide/SD001/src/geom/Polygon.as"  target="_blank">Polygon</a> class is a DisplayObject (it extends Sprite) and implements it&#8217;s own draw method. I&#8217;ve had a lot of fun filling the shapes with textures, but kept it minimal for the example. One technique which I found worked well was to choose two vertices and compute the angle between them. From this I created a transformation matrix to use with <em>Graphics.beginBitmapFill</em>, giving the sketch a more 3 dimensional feel as if the collection of polygons was a 3D mesh with textures mapped to it. I&#8217;ll put these examples on Flickr soon.</p>
<p>If you&#8217;re interested in the source code, it&#8217;s available in my <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://code.google.com/p/soulwire/"  target="_blank">code repository</a> or you can download the archive below (for the demo GUI, I am using <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://minimalcomps.com/"  target="_blank">minimal comps</a> courtesy of Keith Peters and for image encoding, Ian McLean&#8217;s <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.auricom.com/devote/an-asynchronous-vector-optimized-jpeg-encoder"  target="_blank">asynchronous JPEG encoder</a> &#8211; thanks guys :).</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=Subdivision.zip" class="download" title="Recursive Subdivision: Recursive Polygon Subdivision demo and source code"  rel="nofollow"><strong>Download:</strong> Recursive Subdivision</a>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/flash/recursive-polygon-subdivision/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Generative Prints for Ishihara</title>
		<link>http://blog.soulwire.co.uk/art-design/illustration/generative-illustrations-for-ishihara</link>
		<comments>http://blog.soulwire.co.uk/art-design/illustration/generative-illustrations-for-ishihara#comments</comments>
		<pubDate>Fri, 12 Feb 2010 00:28:10 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[Illustration]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Sketchbook]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Drawing]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=1042</guid>
		<description><![CDATA[These are some old prints that I made for an exhibition called Ishihara, back in 2008. They&#8217;re created using a tool I built called Rotator, which degrades vector drawings as they are printed to a bitmap, whilst following the path of a random wander. I found them on an old hard drive and thought I&#8217;d [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/recursive-polygon-subdivision' rel='bookmark' title='Permanent Link: Recursive Polygon Subdivision'>Recursive Polygon Subdivision</a></li>
<li><a href='http://blog.soulwire.co.uk/art-design/illustration/illustrated-iching-hexagrams' rel='bookmark' title='Permanent Link: Illustrated IChing'>Illustrated IChing</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-1043" title="Ishihara Drawing 1" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara-cover.jpg" alt="Ishihara Drawing 1" width="710" height="360" /></p>
<p>These are some old prints that I made for an exhibition called <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.facebook.com/group.php?gid=35280706927" >Ishihara</a>, back in 2008. They&#8217;re created using a tool I built called <em>Rotator</em>, which degrades vector drawings as they are printed to a bitmap, whilst following the path of a random wander. I found them on an old hard drive and thought I&#8217;d share.<span id="more-1042"></span></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara001.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 001" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara001-710x471.jpg" alt="Ishihara Rotator Print 001" width="710" height="471" /></a></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara002.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 002" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara002-710x471.jpg" alt="Ishihara Rotator Print 002" width="710" height="471" /></a></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara003.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 003" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara003-710x471.jpg" alt="Ishihara Rotator Print 003" width="710" height="471" /></a></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara004.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 004" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara004-710x471.jpg" alt="Ishihara Rotator Print 004" width="710" height="471" /></a></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara005.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 005" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara005-710x471.jpg" alt="Ishihara Rotator Print 005" width="710" height="471" /></a></p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara006.jpg"  rel="shadowbox[post-1042];player=img;"><img class="alignnone size-medium wp-image-1044" title="Ishihara Rotator Print 006" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/ishihara006-710x471.jpg" alt="Ishihara Rotator Print 006" width="710" height="471" /></a></p>
<p>On reflection, the morphing shapes mixed with simple line drawings remind me of James Paterson&#8217;s work over at <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.presstube.com" >presstube</a> or Victor Taba&#8217;s <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.victortaba.com/" >animations</a> (but not as good as either). I&#8217;ll see if the hard drive has the Rotator AIR app these were made with on there somewhere too, it could be fun to play around with adding some colour and using more complicated vectors.</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/recursive-polygon-subdivision' rel='bookmark' title='Permanent Link: Recursive Polygon Subdivision'>Recursive Polygon Subdivision</a></li>
<li><a href='http://blog.soulwire.co.uk/art-design/illustration/illustrated-iching-hexagrams' rel='bookmark' title='Permanent Link: Illustrated IChing'>Illustrated IChing</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-tonfall-particle-node-sequencer' rel='bookmark' title='Permanent Link: AS3 Particle Node Sequencer'>AS3 Particle Node Sequencer</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/art-design/illustration/generative-illustrations-for-ishihara/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>BitmapData Colour Palette</title>
		<link>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette</link>
		<comments>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette#comments</comments>
		<pubDate>Sat, 11 Oct 2008 19:52:35 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Colour]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=195</guid>
		<description><![CDATA[My previous post explained and provided a very simple method for extracting colours from a BitmapData image, by averaging the colours in specific areas. This can have several applications, for example it features in a large amount of prototypes for the update to my Motion Tracking engine. However, if you want to create an accurate and [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata' rel='bookmark' title='Permanent Link: BitmapData Average Colours'>BitmapData Average Colours</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/as3-ase-adobe-swatch-exchange-encoder' rel='bookmark' title='Permanent Link: ASE (Adobe Swatch Exchange) Encoder'>ASE (Adobe Swatch Exchange) Encoder</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/colour-palette.swf" title="Extracting the Colour Palette from an Image" rel="lightbox;width=800;height=450;" ><img class="alignnone size-medium wp-image-582" title="Bitmapdata Colour Palette" src="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/bitmapdata-colour-palette-710x399.jpg" alt="Bitmapdata Colour Palette" width="710" height="399" /></a></p>
<p>My <a href="http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata" title="BitmapData average colour" >previous post</a> explained and provided a very simple method for <a href="http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata" title="Extracting the average colour from a BitmapData image" >extracting colours from a BitmapData image</a>, by averaging the colours in specific areas. This can have several applications, for example it features in a large amount of prototypes for the update to my <a href="http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking" title="AS3 Webcam Motion Tracking engine" >Motion Tracking engine</a>. However, if you want to create an accurate and representative colour palette from an image it has several flaws, the most obvious being that by averaging colours, you are actually removing or diluting the striking but perhaps less frequent colours in the image – the very colours which often make an image’s colour palette so exiting!</p>
<p>So, if we’re to extract an exciting and more representative palette from an image, we need a more intelligent algorithm; one which takes into account what makes a colour palette interesting – the contrasts and juxtapositions of colours within the image.<span id="more-195"></span></p>
<p>After some experimentation I arrived at the following solution. <a href="#getcode">I have posted the code bellow</a>, but I think it’s important to understand how it works and why each step is taken, so without further ado, here be my approach to calculating the colour palette of a BitmapData image&#8230;</p>
<h2>Reducing the colours</h2>
<p>We’re going to be performing quite a few operations on the colours in our input image, so for the sake of performance it’s wise to reduce the colours in the image as much as possible without losing the overall look and feel of the palette.</p>
<p><a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://en.nicoptere.net/" title="Nicolas Barradeau's blog"  target="_blank">Nicolas Barradeau</a> has done some really cool things with this, and his <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://en.nicoptere.net/?p=8" title="Colour Depth Change"  target="_blank">Color Depth Change</a> script is really worth checking out. We can actually enhance this technique slightly by omitting the two loops which cycle through every pixel in the image and use <strong>paletteMap</strong>. The result is good enough for our needs and substantially quicker. I’m also glad I could use the BitmapData paletteMap method, because up until now I hadn’t ever had a use for it :)</p>
<p>I’ve found that reducing the image’s colour palette to 64 colours works well performance wise and still looks great, but you might want to use anything up to 256.</p>
<p>I won’t go into how paletteMap works, and <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://livedocs.adobe.com/flex/201/langref/flash/display/BitmapData.html#paletteMap()"  target="_blank">the docs</a> aren’t very helpful on this matter so I suggest you check out Google if you want a bit more information. In short, we create a new index of colours for the image by creating three arrays, one for each channel (red, green and blue) and pass these values to the paletteMap method, which takes care of the rest at blisteringly fast speeds. What we are left with is a dithered version of our original image, allowing us to analyse it’s pixels in a much speedier manner.</p>
<pre lang="actionscript">public static function reduceColours( source:BitmapData, colours:int = 16 ):void
{
	var Ra:Array = new Array(256);
	var Ga:Array = new Array(256);
	var Ba:Array = new Array(256);

	var n:Number = 256 / ( colours / 3 );

	for (var i:int = 0; i < 256; i++)
	{
		Ba[i] = Math.floor(i / n) * n;
		Ga[i] = Ba[i] << 8;
		Ra[i] = Ga[i] << 8;
	}

	source.paletteMap( source, source.rect, new Point(), Ra, Ga, Ba );
}</pre>
<p>Note: at this stage, if you’re working with a very large image, it’s advisable to draw the image to a smaller BitmapData using a scaled Matrix, as we will be looping over its pixels and so a 2000 x 2000 image is likely to make your CPU rather pissed off at you!</p>
<h2>Indexing the colours</h2>
<p>The next step is to build an index of the colours in the image. By index, I mean that we want a list of unique colours and a tally for each telling us how many times they occur in the image. We can do this by using an Object or a Dictionary, which uses the colour values as a key and a counter as the value.</p>
<pre lang="actionscript">public static function indexColours( source:BitmapData, sort:Boolean = true ):Array
{

	var n:Object = {};
	var a:Array = [];
	var p:int;

	for (var x:int = 0; x < source.width; x++)
	{
		for (var y:int = 0; y < source.height; y++)
		{
			p = source.getPixel(x, y);
			n[p] ? n[p]++ : n[p] = 1;
		}
	}

	for (var c:String in n)
	{
		a.push ( { colour:c, count:n[c] } );
	}

	function byCount( a:Object, b:Object ):int
	{
		if ( a.count > b.count ) return 1;
		if ( a.count < b.count ) return -1;
		return 0;
	}

	return a.sort( byCount, Array.DESCENDING );
}</pre>
<p>We are left with an Object containing all the colours in the image, grouped by their colour value and with a reference to how frequently they appear. We can then use a <em>for in</em> loop to create an array from the Objects properties.</p>
<p>Finally, we need to sort the resulting Array, essentially by popularity, so that the colours which appear most frequently within the image are at the start of the Array. We can do this using the Array’s sort method, and passing a custom function which compares each colour’s count or frequency to that of the other colours. Now we can discard the count value, and what we are left with is a correctly ordered array of unsigned integers representing our entire spectrum of colours.</p>
<h2>Finding unique, contrasting colours</h2>
<p>At this point, we could simply take the first values from the array and call this our palette, after all if we wanted, say, a 16 colour palette then we know that the first 16 colours in our Array are the most frequently occurring colours in our source image. The problem with this is that, as with most things in life, just because something is popular doesn’t necessarily make it good! Take a landscape photograph for example; there may be a beautiful collection of flowers with striking colours in the foreground, and a burning orange and pink sunset descending over the horizon, yet the first group of colours in our Array will likely be a host of different shades of green from the hills and fields – not exactly what we were hoping for!</p>
<p>So we need an algorithm which can discern between colours and tell us which of our colours have a sufficient variance, therefore producing a palette which fairly represents the broader spectrum of colours in our image.</p>
<p>The best solution that I found was to add up the square of the red, green and blue components of two colours and compare their results. If they are sufficiently different (as determined by a variable tolerance) then we have a match.</p>
<pre lang="actionscript">public static function similar( colour1:uint, colour2:uint, tolerance:Number = 0.01 ):Boolean
{
	var RGB1:Object = Hex24ToRGB( colour1 );
	var RGB2:Object = Hex24ToRGB( colour2 );

	tolerance = tolerance * ( 255 * 255 * 3 ) << 0;

	var distance:Number = 0;

	distance += Math.pow( RGB1.red - RGB2.red, 2 );
	distance += Math.pow( RGB1.green - RGB2.green, 2 );
	distance += Math.pow( RGB1.blue - RGB2.blue, 2 );

	return distance <= tolerance;
}</pre>
<p>To apply this idea, we need to create an empty Array which will eventually become our results. We then begin to loop through our colours, taking the first and comparing it to subsequent colours until we find one which is sufficiently different. We then push this colour into our results Array, and then continue searching, this time comparing each colour in our initial Array to each colour in our growing Array of unique colours. Once we have reached our predefined quota of colours, or the end of the Array, we have our beautiful colour palette!</p>
<pre lang="actionscript">public static function different( colour:uint, colours:Array, tolerance:Number = 0.01 ):Boolean
{
	for (var i:int = 0; i < colours.length; i++)
	{
		if ( similar( colour, colours[i], tolerance ) )
		{
			return false;
		}
	}
	return true;
}

public static function uniqueColours( colours:Array, maximum:int, tolerance:Number = 0.01 ):Array
{
	var unique:Array = [];

	for (var i:int = 0; i < colours.length &#038;&#038; unique.length < maximum; i++)
	{
		if ( different( colours[i], unique, tolerance ) )
		{
			unique.push( colours[i] );
		}
	}

	return unique;
}</pre>
<h2 name="getcode" id="getcode">Putting it all together</h2>
<p>I’ve packaged the above technique, as well as the <strong>averageColour </strong>and <strong>averageColours </strong>methods from my last post into a <strong>ColourUtils</strong> class. Most of the methods detailed above, despite being necessary steps in finding an image’s colour palette, are useful in their own right and so I have separated them out into a documented collection of static methods.</p>
<p>You can download the <strong>ColourUtils </strong>class and also some examples of how to use it:</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=ColourUtils.zip" class="download" title="ColourUtils: A useful class for extracting colour palettes from images and BitmapData objects based on an interestingness algorithm, ensuring contrasting colours are selected."  rel="nofollow"><strong>Download:</strong> ColourUtils</a> <a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=ColourUtils-Demo.zip" class="download" title="ColourUtils Demo: An example of how to use the ColourUtils class to extract a colour palette from an image or BitmapData."  rel="nofollow"><strong>Download:</strong> ColourUtils Demo</a>
<h2>Possible Enhancements</h2>
<p>I have a few ideas for possible enhancements to the algorithm, and <strong>would like to hear yours</strong> if you have any. Currently, these are my intentions for the next revision:</p>
<ul>
<li>Integration of the <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.colourlovers.com/blog/2007/09/02/the-muller-formula-or-predictable-color-preferences/" >Müller formula</a> so that a single colour from a group of similar colours is chosen not by its frequency but by its suitability for the extracted palette – i.e. a colour with greater tonal variation is preferred by the algorithm much the same way as it would be by the eye.</li>
<li>Palette colour sorting by hue, saturation or brightness.</li>
<li>A faster way of discarding unwanted colours, preferably before looping through the colour index, resulting in much better performance.</li>
</ul>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata' rel='bookmark' title='Permanent Link: BitmapData Average Colours'>BitmapData Average Colours</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/as3-ase-adobe-swatch-exchange-encoder' rel='bookmark' title='Permanent Link: ASE (Adobe Swatch Exchange) Encoder'>ASE (Adobe Swatch Exchange) Encoder</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette/feed</wfw:commentRss>
		<slash:comments>59</slash:comments>
		</item>
		<item>
		<title>BitmapData Average Colours</title>
		<link>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata</link>
		<comments>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata#comments</comments>
		<pubDate>Fri, 10 Oct 2008 18:21:46 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Colour]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=165</guid>
		<description><![CDATA[If you want a very simple way of extracting a colour palette from an image, one technique would be to average the colour values within specific areas. Averaging colour values is almost identical to averaging numbers, except with the added initial step of finding the red, green and blue components of the colour. To do [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/as3-ase-adobe-swatch-exchange-encoder' rel='bookmark' title='Permanent Link: ASE (Adobe Swatch Exchange) Encoder'>ASE (Adobe Swatch Exchange) Encoder</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/average-colour.swf" rel="lightbox;width=800;height=450;" title="Finding the average colours in an image" ><img src="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/average-colours-710x399.jpg" alt="BitmapData Average Colours" title="BitmapData Average Colours" width="710" height="399" class="alignnone size-medium wp-image-618" /></a></p>
<p>If you want a very simple way of extracting a colour palette from an image, one technique would be to average the colour values within specific areas. Averaging colour values is almost identical to averaging numbers, except with the added initial step of finding the red, green and blue components of the colour. To do this we can use <strong>bitwise operators</strong>, in this case <strong>bitwise shift</strong>, to perform fast operations on each <em>bit </em>inside the unsigned integer returned by <em>getPixel</em> or <em>getPixel32</em>.  If you want to know more about bitwise operators, <strong>Moock </strong>has written a detailed and, as ever, very clear article on where, when and why to use bitewise operations. You can read it <a rel="nofollow" href="http://blog.soulwire.co.uk//goto/http://www.moock.org/asdg/technotes/bitwise/"  target="_blank">here</a>.</p>
<p>So once you’re familiar with how to shift the bits of an integer, you can easily get the RGB values from a 24 bit hexadecimal by moving the bits to the right by a certain amount using the <strong>bitwise right </strong><strong>shift </strong> operator (<strong>&gt;&gt;</strong>).<span id="more-165"></span></p>
<p>For example, getting the red, green and blue values from a 24 bit integer would look like:</p>
<pre lang="actionscript">var colour:uint = 0x33CC99;

var R:Number = colour &gt;&gt; 16 &amp; 0xFF;
var G:Number = colour &gt;&gt; 8  &amp; 0xFF;
var B:Number = colour &amp; 0xFF;</pre>
<p>And finding the alpha, red, green and blue values of a 32 bit integer:</p>
<pre lang="actionscript">var colour:uint = 0xFF33CC99;

var A:Number = colour &gt;&gt; 24 &amp; 0xFF;
var R:Number = colour &gt;&gt; 16 &amp; 0xFF;
var G:Number = colour &gt;&gt; 8 &amp; 0xFF;
var B:Number = colour &amp; 0xFF;</pre>
<p>So we know that by shifting the bits to the right, we can effectively break an unsigned integer representing a colour into its specific components, but what about changing these components back into an RGB or ARGB value? Well, it’s simply a matter of shifting the bits in the other direction, using the <strong>bitwise left shift </strong>operator, which looks like this <strong>&lt;&lt;</strong> (two less than operators next to each other).</p>
<p>So using this bitwise shift left operator, you can take your RGB or ARGB values and cram the little buggers back into a usable format, with a little help from <em>bitwise OR</em>:</p>
<pre lang="actionscript">// RGB
var colourRBG:uint = (R &lt;&lt; 16 | G &lt;&lt; 8 | B);

// ARGB
var colourARBG:uint = (A &lt;&lt; 24 | R &lt;&lt; 16 | G &lt;&lt; 8 | B);</pre>
<p>Right, so we know how to take an unsigned integer, for example one that’s been returned from <strong>getPixel </strong>or <strong>getPixel32 </strong>and break it down into its <strong>RGB </strong>or <strong>ARGB </strong>components &#8211; and then for the sake of universal harmony, put it back together again and release it back into its 24 or 32bit world with all its binary friends.</p>
<p>So now, finding the average colour within a set of colours is simply a question of averaging the red, green and blue values of all the colours, and then turning these averages into a new colour.</p>
<p>The method bellow does just this, by looping through the pixels in a BitmapData object, adding up all of the red, green and blue values, dividing them by the total number of pixels and then creating a new colour from the results.</p>
<pre lang="actionscript">public static function averageColour( source:BitmapData ):uint
{
	var red:Number = 0;
	var green:Number = 0;
	var blue:Number = 0;

	var count:Number = 0;
	var pixel:Number;

	for (var x:int = 0; x &lt; source.width; x++)
	{
		for (var y:int = 0; y &lt; source.height; y++)
		{
			pixel = source.getPixel(x, y);

			red += pixel &gt;&gt; 16 &amp; 0xFF;
			green += pixel &gt;&gt; 8 &amp; 0xFF;
			blue += pixel &amp; 0xFF;

			count++
		}
	}

	red /= count;
	green /= count;
	blue /= count;

	return red &lt;&lt; 16 | green &lt;&lt; 8 | blue;
}</pre>
<p>So taking this a step further; say we want an array of 64 colours from an image, we can break the input image down into 64 chunks and find the averages of each. The easiest way of doing this is to build a grid, copy the pixels in each cell and use the averageColour function to return the average colour value of that cell.</p>
<pre lang="actionscript">public static function averageColours( source:BitmapData, colours:int ):Array
{
	var averages:Array = new Array();
	var columns:int = Math.round( Math.sqrt( colours ) );

	var row:int = 0;
	var col:int = 0;

	var x:int = 0;
	var y:int = 0;

	var w:int = Math.round( source.width / columns );
	var h:int = Math.round( source.height / columns );

	for (var i:int = 0; i &lt; colours; i++)
	{
		var rect:Rectangle = new Rectangle( x, y, w, h );

		var box:BitmapData = new BitmapData( w, h, false );
		box.copyPixels( source, rect, new Point() );

		averages.push( averageColour( box ) );
		box.dispose();

		col = i % columns;

		x = w * col;
		y = h * row;

		if ( col == columns - 1 ) row++;
	}

	return averages;
}</pre>
<p>In terms of building an accurate colour palette from an image, this isn’t a great method, mainly because averaging the colours doesn’t give you a fair representation of the <em>range</em> of colours in the image. The palette returned can often be somewhat muddy; however it is still a technique that I’ve found a use for on a surprisingly regular basis and so thought it worth sharing. Becoming familiar with bitwise operators is also a useful exercise and so, if they aren’t already part of your life, I suggest you begin to woo them with your nerdy charm.</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/as3-ase-adobe-swatch-exchange-encoder' rel='bookmark' title='Permanent Link: ASE (Adobe Swatch Exchange) Encoder'>ASE (Adobe Swatch Exchange) Encoder</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
	</channel>
</rss>

