2015-10-23

A Note For Readers: This is a long question, but it needs a background to understand the question asked.

The color quantization technique is commonly used to get the dominant colors of an image.
One of the well-known libraries that do color quantization is Leptonica through the Modified Median Cut Quantization (MMCQ) and octree quantization (OQ)
Github's Color-thief by @lokesh is a very simple implementation in JavaScript of the MMCQ algorithm:

Technically, the image on a <img/> HTML element is backed on a <canvas/> element:

And that is the problem with TVML, as we will see later on.

Another implementation I recently came to know was linked on this article Using imagemagick, awk and kmeans to find dominant colors in images that links to Using python to generate awesome linux desktop themes.
The author posted an article about Using python and k-means to find the dominant colors in images that was used there (sorry for all those links, but I'm following back my History...).

The author was super productive, and added a JavaScript version too that I'm posting here: Using JavaScript and k-means to find the dominant colors in images

In this case, we are generating the dominant colors of an image, not using the MMCQ (or OQ) algorithm, but K-Means.
The problem is that the image must be a as well:

and then

This is because the Canvas has a getContext() method, that expose 2D image drawing APIs - see An introduction to the Canvas 2D API

This context ctx is passed to the image processing function

So you can draw an image on the Canvas through the Context and get image data:

Another nice solution is in CoffeeScript, ColorTunes, but this is using a as well:

But, wait, we have no <canvas/> element in TVML!

Of course, there are native solutions like Objective-C ColorCube, DominantColor - this is using K-means

and the very nice and reusable ColorArt by @AaronBrethorst from CocoaControls.

Despite the fact that this could be used in a TVML application through a native to JavaScriptCore bridge - see tvOS: How to bridge TVML/JavaScriptCore to UIKit/Objective-C (Swift)?

my aim is to make this work completely in TVJS and TVML.

The simplest MMCQ JavaScript implementation does not need a Canvas: see Basic Javascript port of the MMCQ (modified median cut quantization) by Nick Rabinowitz, but needs the RGB array of the image:

that is taken from the HTML <canvas/> and that is the reason for it!

So, how to achieve this result of getting in pure JavaScript RGB array from an image without the <canvas/> element?

[UPDATE]
I have posted this question to Color-Thief github repo, adapting the RGB array calculations to the latest codebase.
The solution I have tried was this

but it does not gives back the right RGB colors array.

Show more