<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/how-to-build-a-color-palette-from-any-image-with-r-and-k-means-algo/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.milanor.net/blog/build-color-palette-from-image-with-paletter/"> MilanoR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p>Some weeks ago, I was working on a dataviz to show results coming from an analysis I had performed, and I found myself looking at that default ggplot2 palette, which is optimal in term of discrimination among categories, but nevertheless can not be compared to some wonderful palettes you can see employed within art masterpieces like Monet <a rel="nofollow" href="https://it.wikipedia.org/wiki/Impressione,_levar_del_sole#/media/File:Monet_-_Impression,_Sunrise.jpg" target="_blank"><em>impression,soleil levant</em></a> or Michelangelo’s <a rel="nofollow" href="https://it.wikipedia.org/wiki/Tondo_Doni#/media/File:Michelangelo_Buonarroti_046.jpg" target="_blank"><em>Tondo Doni</em></a>. Those palettes are coming from years and years of studies around colour theory and pictorial techniques and, I started thinking, would do a great service if employed as plot’s palettes, with their complementary colours or their balanced set of hues.</p>
<div class="wp-caption"><a rel="nofollow" href="https://i2.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-1.jpg" target="_blank"><img sizes="(max-width: 700px) 100vw, 700px" src="https://i2.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-1-300x233.jpg?w=450" alt="paletteR-1" class="wp-image-2689" data-recalc-dims="1"></a>
<p class="wp-caption-text">Impression, soleil levant. Monet</p>
</div>
<p>But, how to do it? The probably most obvious answer would have involved downloading one of these masterpieces, find out a website with point and click colour picking featyre and build a palette from it. Nevertheless since I am a lazy programmer I found an easier way to do it, I found out how to build a color palette from any custom image in R.</p>
<div>
<h2>what you are going to find here</h2>
<p>The post will give you a clear view of how the task was automated, providing detail of the clustering algorithm employed. It will moreover show you a small R package which was developed to ease the application of this process from other users. Finally use cases for the developed algo will be provided, from the most intuitive ggplot2 employment to the more advanced one.</p>
</div>
<div>
<h2>behind the scenes: k-means for image processing</h2>
<p>I have to be honest: my first thinking when dealing with this task was not the one I am going to show you. I was actually getting lost following a bad path made of triples of Red Green and Blues, trying to select from frequency tables the most representative ones. But suddenly, after reading a blog post about k-means algorithm the idea was born: let k-means divide the picture into homogeneous clusters, having each one a “center” constituted by an RGB triple and by this way define a palette representative of the picture itself.</p>
<div>
<h3>the k-means algorithm</h3>
<p>To let you maximize the fun coming from the rest of the post we have to see here briefly what the k-means clustering algorithm is. This algo is a way to divide a given set of data into k homogeneous groups/clusters, where k stands for a number, like usually n does. How do we do that? The basic and elegant idea behind the algorythm is: measure the difference between data points and look for the clusterisation which minimize this difference within clusters. The typical measure employed here is the euclidean distance, and particularly the <em>squared euclidean distance</em>. We measure with it the distance between points, and we can expand it from 1 to n dimensions. That is why it turns to be effective with such kind of problems where populations can be pertaining to multidimensional spaces. Making it less wordy, let us look at the formula behind the distance. Given two points of a three dimension space <span><img alt="P=(p_{x},p_{y},p_{z})" src="https://i1.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_0c2201df15e0d4a808ce4d8f4067fd64.gif?w=456" data-recalc-dims="1"></span> and <span><img alt="Q=(q_{x},q_{y},q_{z})" src="https://i2.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_1759477bf504265bc523d458c1009730.gif?w=456" data-recalc-dims="1"></span> this distance is measured as the square of the distance between the three couples of coordinates raised to the the second:</p>
<p><span><img alt="{sqrt{(p_{x}-q_{x})^{2}+(p_{y}-q_{y})^{2}+(p_{z}-q_{z})^{2}}}" src="https://i1.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_a8c68b21ee5b73b93bfa139a6b92d709.gif?w=456" data-recalc-dims="1"></span></p>
<p>Now that we know the measure we want to minimize let us have a look at how to find the best possible clusterisation. The typical way adopted from k-means algorithm is working on iterations:</p>
<ul>
<li><em>(a)</em>: first iteration randomically assigns a cluster to each data point</li>
<li><em>(b)</em>: then it measures the centroid for every cluster</li>
<li><em>(c)</em>: changes cluster assignation moving each data point to the cluster which have the centroid closer to the data point</li>
<li><em>(d)</em>: measures the euclidean distance within clusters and sums it up to measure the performance of the given clusterisation</li>
<li><em>(e)</em>: then the algo iterates <em>(b)</em>, <em>(c)</em> and <em>(d)</em> until the last step does not obtain sum of distances lower than the previous one.</li>
</ul>
<p>You may be wondering what exactly a centroid it. To get it just think it is the barycenter of a given set of point. Formally it is the point which minimises the euclidean distance between him and the other points within the group. for a given set of <span><img alt="n" src="https://i2.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_7b8b965ad4bca0e41ab51de7b31363a1.gif?w=456" data-recalc-dims="1"></span> points in a <span><img alt="mathbb{R}^{n}" src="https://i2.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_f65c4f70e25cf0c782818fa85ab12bb7.gif?w=456" data-recalc-dims="1"></span> space we measure it as follow:</p>
<p><span><img alt="mathbf{C}={frac{mathbf{x}_{1}+mathbf{x}_{2}+cdots+mathbf{x}_{n}}{n}}" src="https://i0.wp.com/www.milanor.net/blog/wp-content/plugins/latex/cache/tex_cb6530a05ad57c22b6b5f73e42c76b31.gif?w=456" data-recalc-dims="1"></span></p>
<p>Now that we know what a k-means algorithm is, how do we apply it to an image?</p>
</div>
</div>
<div>
<h3>applying the k-means algorithm to an image</h3>
<p>Getting a closer look to an image we find it can be decomposed into reasonably small points, each of which is of a single colour. This is what for instance the pointillisme thought a long time before pc’s. Pointillists started painting on canvas not mixing their colours in greater or smaller colour fields but rather applying them as small points one next to the other. Take for instance this famous painting from Georges Seurat:</p>
</div>
<p> </p>
<div>
<div class="wp-caption"><a rel="nofollow" href="https://i0.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-2.jpg" target="_blank"><img sizes="(max-width: 800px) 100vw, 800px" src="https://i1.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-2-1024x688.jpg?w=450" alt="Un dimanche après midi a l’ile de la Grande Jatte. Seurat" class="wp-image-2690" data-recalc-dims="1"></a>
<p class="wp-caption-text">Un dimanche après midi a l’ile de la Grande Jatte. Seurat</p>
</div>
</div>
<p>Can you see the vibrant small dots?</p>
<p>Decomposing an image to its constitutent points is the first needed step to apply on it every kind of statistical, algorithmical or matematical concept. Once this is done, at least within our mind, we have to find a way to univocally identify every single point. This is easily done in the space, since we are dealing with flat images and the good old cartesian x-y couple will be enough. But what about colours? We are looking here for a way to derive a palette from every kind of possible image, shouldn’t we find a way to “measure” the color of points? To get this done we will resort here to the RGB codification, a convenient way to measure colours firstly introduced during the ’800 which became popular during the age of televisions and electronical monitors (you know, they need a way to measure colours too).</p>
<p>Following this theory there are three primary additive colours: Red, Green and Blue. All other colours can be obtained mixing these three colours in different proportions. Each colour can be therefore decomposed into a triple of this colours. Give a look for instance at this green:</p>
<p><a rel="nofollow" href="https://i1.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-3.png" target="_blank"><img sizes="(max-width: 201px) 100vw, 201px" src="https://i1.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-3.png?resize=201%2C197" alt="paletteR-3" class="wp-image-2691" data-recalc-dims="1"></a></p>
<p>following RGB codification scheme we can decompose it as follow:</p>
<ul>
<li>Red 120</li>
<li>Green 214</li>
<li>Blue 23</li>
</ul>
<p>as you can see we now have an objective way to measure and describe colours. We can therefore take our picture and describe it as a set of points each of which with a codified colour, in terms of Red Green and Blue. Let us try to do it for real, importing an image into our R environment.</p>
<div>
<h4>read the image</h4>
<p>As is often the case within the R world, we have a package to help us with this task. The jpeg package, developed by <a rel="nofollow" href="http://urbanek.info/" target="_blank">Simon Urbanek</a> provides us functions to import an image and decomposing it into points each of which codified in the terms of the RGB system. Once the package is installed you can run the <em>readJPEG()</em> function to import and decompose every kind of .jpeg image. within our example we are going to employ the <em>Sacra Famiglia Canigiana</em> painting by Raffaello, which contains a wonderful set of vivid colours coming from Raffaello’s studies on the <em>unione</em> painting technique.</p>
</div>
<div class="wp-caption"><a rel="nofollow" href="https://i2.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-4.jpg" target="_blank"><img sizes="(max-width: 450px) 100vw, 450px" src="https://i2.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-4.jpg?resize=450%2C551" alt="Sacra famiglia Canigiani. Raffaello" class="wp-image-2692" data-recalc-dims="1"></a>
<p class="wp-caption-text">Sacra famiglia Canigiani. Raffaello</p>
</div>
<div>
<p>To employ it we have to download it into our environment, which can be easily done via the <em>download.file()</em> function. Once we are done with this we can apply the readJPEG function described above, assigning the result to the <em>painting</em> object:</p>
<pre>download.file(&quot;https://andreacirilloac.github.io/dataviz/images/sacra_famiglia_canigiani.jpg&quot;, &quot;image.jpg&quot;)
painting     &lt;- readJPEG(&quot;image.jpg&quot;)</pre>
<p>We now have an object, called painting, composed by a set of triples, where each triple stores values of Red Green and Blue. This object is actually an array, i.e. a multi-dimensional matrix. If you are not familiar with this kind of objects in R you can give a look to the short introduction from Hadley Whickam within <a rel="nofollow" href="http://adv-r.had.co.nz/Data-structures.html#matrices-and-arrays" target="_blank">Advanced R</a>.</p>
<p>Next logical step is to create an object feasible for k-means algorithm application. We therefore derive from the painting object a new data frame, storing for each point x-y coordinates and our beloved triples:</p>
<pre>dimension    &lt;- dim(painting)
painting_rgb &lt;- data.frame(
  x = rep(1:dimension[2], each = dimension[1]),
  y = rep(dimension[1]:1, dimension[2]),
  R = as.vector(painting[,,1]), #slicing our array into three
  G = as.vector(painting[,,2]),
  B = as.vector(painting[,,3])
)</pre>
<p>just to be sure things are going on as we imagine, let us have a look to the <em>painting_rgb</em> object</p>
<pre>head(painting_rgb)</pre>

<pre>##   x   y         R         G         B
## 1 1 551 0.9490196 0.8941176 0.8823529
## 2 1 550 0.9333333 0.8784314 0.8666667
## 3 1 549 0.9450980 0.9019608 0.8784314
## 4 1 548 0.9215686 0.8784314 0.8549020
## 5 1 547 0.9529412 0.9176471 0.8901961
## 6 1 546 0.9294118 0.8941176 0.8588235</pre>
</div>
<div>
<h4>run k-means</h4>
<p>we are now ready to apply k-means algorithm to our data. It is actually really easy to apply this algo in R. As is often the case with R this quite advanced algo is already made available within the base R package, stored within the function conveniently named <em>kmeans()</em>. We just have to pass to this function the dataset over which we want to apply the algo, specifying the number of clusters. We could also specify some other settings, like the maximum number of iterations of above introduced steps <em>(b)</em> <em>(c)</em> and <em>(d)</em>.</p>
<pre>k_means        &lt;- kmeans(painting_rgb[,c(&quot;R&quot;,&quot;G&quot;,&quot;B&quot;)], centers = 20, iter.max = 30)</pre>
</div>
<div>
<h4>dealing with results</h4>
<p>As you can see we applied the kmeans function passing as dimensions R G and B and a number of clusters equal to 30. We also specified 30 iterations as the maximum number of loops to try to converge. We now have a <em>k_means</em> object, what is its shape? let us investigate this running <em>str()</em> on it:</p>
<pre>str(k_means)</pre>

<pre>## List of 9
##  $ cluster     : int [1:247950] 9 9 9 9 9 9 9 9 9 9 ...
##  $ centers     : num [1:20, 1:3] 0.3981 0.7117 0.7668 0.6133 0.0958 ...
##   ..- attr(*, &quot;dimnames&quot;)=List of 2
##   .. ..$ : chr [1:20] &quot;1&quot; &quot;2&quot; &quot;3&quot; &quot;4&quot; ...
##   .. ..$ : chr [1:3] &quot;R&quot; &quot;G&quot; &quot;B&quot;
##  $ totss       : num 60652
##  $ withinss    : num [1:20] 85 36.6 75.2 43 28.6 ...
##  $ tot.withinss: num 1048
##  $ betweenss   : num 59604
##  $ size        : int [1:20] 15268 4833 9924 15967 32370 16001 13773 2297 10450 10684 ...
##  $ iter        : int 10
##  $ ifault      : int 0
##  - attr(*, &quot;class&quot;)= chr &quot;kmeans&quot;</pre>
</div>
<div>
<h4>showing the palette</h4>
<p>without analysing every single attribute we can easily locate the <em>centers</em> vector, showing the above mentioned centroids. As you would imagine, those centroids have got three dimensions: one for the R, one for the G and one for the B. And those centroids are points whose minimise the distance from the other points within their cluster. So they are RGB triples representative of homogenous clusters of other RGB triples composing our image. What do you think, is this enough to be a representative palette? Let us check it in the best possible way, i.e. letting our eyes scrutinize them. To do this we are going to leverage the <em>show_col()</em> function from the scales package (once more, thank you Hadley Whickam):</p>
<pre>show_col(rgb(k_means$centers))</pre>
</div>
<p><a rel="nofollow" href="https://i0.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-5-e1497969924559.png" target="_blank"><img sizes="(max-width: 500px) 100vw, 500px" src="https://i0.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-5-e1497969924559.png?w=450" alt="" class="wp-image-2693" data-recalc-dims="1"></a></p>
<div>
<div>
<div>
<p>Here it is our freshly and autonomously made palette, which greatly represents the main hues of Raffaello’s painting.</p>
</div>
</div>
</div>
<div>
<h2>paletter package to replicate the process</h2>
<p>One of the best gifts every R user receives from the R community is the ton of packages available to accomplish nearly every data mining task. This is why I often try to translate my code into packages, especially when it contains some functions which could be useful for someone. This I think is the case for the processing steps we have seen before, as we will see later on. For this reason you can find <a rel="nofollow" href="https://github.com/AndreaCirilloAC/paletter" target="_blank">on Github a packge named paletter</a>, which provides you the palette_maker function, to let you easily apply the above introduced algo on your custom image. Paletter is freely available (of course…), is not so badly documented, and you can install it running the following:</p>
<pre>library(devtools)
install_github(&quot;andreacirilloac/paletter&quot;)</pre>

<pre>## Skipping install of 'paletter' from a github remote, the SHA1 (66780b00) has not changed since last install.
##   Use `force = TRUE` to force installation</pre>
<p>once you will be done with the installation running the algo will be even easier, requiring you to run the <em>palette_maker</em> function, which takes as input the path to the picture and the number of colours you are wishing to derive from it:</p>
<pre>library(paletter)
download.file(&quot;https://andreacirilloac.github.io/dataviz/images/sacra_famiglia_canigiani.jpg&quot;, &quot;image.jpg&quot;)
colours_vector &lt;- palette_maker(&quot;image.jpg&quot;, number_of_colors = 32)</pre>

<pre>## Warning: Quick-TRANSfer stage steps exceeded maximum (= 12397500)</pre>
</div>
<p><a rel="nofollow" href="https://i1.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-6.png" target="_blank"><img sizes="(max-width: 700px) 100vw, 700px" src="https://i1.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-6.png?w=450" alt="" class="wp-image-2694" data-recalc-dims="1"></a></p>
<div>
<p>as you see the function results into the palette being printed out and a vector of esadecimal RGB values. If you are wondering why we specified 32 as number of colours, you just have to read a bit more on to discover it.</p>
</div>
<div>
<h2>use cases</h2>
<p>As simple as this idea is it is nevertheless quite a useful one, since it has different possible use cases. The most obvious which comes to mind is to employ this palette within a ggplot plot, and we will see how to do it. Moreover some other more dynamic ideas are exposed below.</p>
<div>
<h3>how to use the palette in ggplot</h3>
<p>To employ this palette within a ggplot plot you have to go over the predefined palette recalled inside the ggplot() function. To do this you have at your disposal the <em>scale_colour_manual</em> function, which allows you to specify a vector of RGB values to be employed as palette. We just have to be sure to pass a sufficient number of colours, based on the number of groups we are trying to show. Find below an example of application on the well known <em>mtcars</em> data:</p>
<pre>ggplot(data = mtcars, aes(
x = disp,
y = hp,
color = rownames(mtcars)
)) +
geom_point(stat = 'identity', aes(size = cyl)) +
scale_color_manual(values = colours_vector) +
theme_minimal() +
geom_text(label = rownames(mtcars),
color = 'grey40',
check_overlap = TRUE) +
guides(size = FALSE) +
theme(legend.position = &quot;bottom&quot;) +
labs(title = &quot;disp vs hp&quot;)</pre>
</div>
</div>
<p><a rel="nofollow" href="https://i0.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-7.png" target="_blank"><img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/www.milanor.net/blog/wp-content/uploads/2017/06/paletteR-7.png?w=450" alt="paletteR-7" class="wp-image-2695" data-recalc-dims="1"></a></p>
<div>
<p>can you see now why we set 32 as number of colours to be drawn from the painting? No? ok, just count the number of cars…</p>
</div>
<div>
<h3>alternative use cases</h3>
<p>abstracting from this use case, what we have here? a flexible tool to derive a set of representative colours from an image. We could employ this in several fields:</p>
<ul>
<li>web design: dinamically generate the set of colour to fill web pages based on a main image which should set the tone of all the website</li>
<li>graphics: strarting from something defining the graphical identity of a company, for instance a logo or some kind of picture, easily derive a representative palette to be employed on marketing materials and similar stuffs.</li>
<li>images placeholder: have you noticed that on google images the actual loading of the picture is preceeded from a coloured square filled with a colour representative of the incoming picture? we could do this with paletter, just specifying 1 when setting the number of colours</li>
</ul>
<p>Have you got any other idea? Feel free to comment here suggesting further developments or use cases.</p>
</div>
<p> </p>
</div>
<p>The post <a rel="nofollow" href="http://www.milanor.net/blog/build-color-palette-from-image-with-paletter/" target="_blank">How to build a color palette from any image with R and k-means algo</a> appeared first on <a rel="nofollow" href="http://www.milanor.net/blog" target="_blank">MilanoR</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.milanor.net/blog/build-color-palette-from-image-with-paletter/"> MilanoR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/QBbARuuS_68" height="1"></a></div>