diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c980350 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution; +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..afdfe50 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b5f4a87 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Art Palette + +[Art Palette](https://artsexperiments.withgoogle.com/artpalette/) is part of [Arts & Culture experiments](https://experiments.withgoogle.com/arts-culture), which explore innovative +ways for users to interact with art collections. With [Art Palette](https://artsexperiments.withgoogle.com/artpalette/), you can +search for artworks that match a color combination of your choice. + +![Art Palette](palette_example.jpg?raw=true) + +# Develop + +Some elements of the site are not in the repository but it gives you the base code and concepts to build your own efficient search by palette tool. + +The source code is separate in two parts : + +1. The frontend Javascript code used to extract the color palette from an image. +2. The backend Python code used to find the nearest palettes matching a given one with the palette embedding TensorFlow model. + +## Palette Extraction (frontend) + +Javascript palette extractor that returns the palette calculated for an [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData). + +## Palette Embedding (backend) + +Machine learning model that returns an embedding of color palettes in an Euclidean space that preserves perceptual distance. This embedding enables efficient nearest-neighbor search. + +## Contributors + +[Etienne Ferrier](https://github.com/EtienneFerrier) and [Simon Doury](https://github.com/voglervoice) with friends at the Google Art & Culture Lab. + +## License + +Copyright 2018 Google Inc. + +Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +## Final Thoughts + +We encourage open sourcing projects as a way of learning from each other. Please respect our and other creators’ rights, including copyright and trademark rights when present, when sharing these works and creating derivative work. If you want more info on Google's policy, you can find that [here](https://www.google.com/permissions/). + +N.B.: *This is not an official Google product.* diff --git a/palette-embedding/README.md b/palette-embedding/README.md new file mode 100644 index 0000000..c6871f6 --- /dev/null +++ b/palette-embedding/README.md @@ -0,0 +1,14 @@ +# Palette Embedding + +The palette embedding model is a neural network that projects 5-color palettes into a 15-dimensional space. In this new space, the euclidean distance between embeddings is a perceptual distance between the original color palettes. For instance, mostly red palettes will be close to one another and far from mostly green palettes. + +This euclidean space enables efficient nearest-neighbor search in a set of palettes. + +## Using the library + +The library contains the following classes and a demo showcases how to use these classes. + +* The `PaletteEmbeddingModel` class enables embedding color palettes. + +* The `PaletteSearchIndex` is a data structure that uses the embedding model for efficient nearest-neighbor search. + diff --git a/palette-embedding/model/saved_model.pb b/palette-embedding/model/saved_model.pb new file mode 100755 index 0000000..d1f41ec Binary files /dev/null and b/palette-embedding/model/saved_model.pb differ diff --git a/palette-embedding/model/variables/variables.data-00000-of-00001 b/palette-embedding/model/variables/variables.data-00000-of-00001 new file mode 100755 index 0000000..c457c30 Binary files /dev/null and b/palette-embedding/model/variables/variables.data-00000-of-00001 differ diff --git a/palette-embedding/model/variables/variables.index b/palette-embedding/model/variables/variables.index new file mode 100755 index 0000000..0df33e3 Binary files /dev/null and b/palette-embedding/model/variables/variables.index differ diff --git a/palette-embedding/python/palette_embedding.py b/palette-embedding/python/palette_embedding.py new file mode 100644 index 0000000..065bdff --- /dev/null +++ b/palette-embedding/python/palette_embedding.py @@ -0,0 +1,267 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Demo of the palette embedding model. + +Tested with Tensorflow version 1.3.0. + +Usage example: +$ cd art-palette/palette-embedding/python +$ python palette_embedding.py +""" + +import annoy +import numpy as np +from skimage import color +import tensorflow as tf + +# Parameters of the embedding model. +MODEL_DIR = '../model' +TAG = tf.saved_model.tag_constants.SERVING +SIGNATURE_KEY = ( + tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY) +IN_TENSOR_KEY = tf.saved_model.signature_constants.PREDICT_INPUTS +OUT_TENSOR_KEY = tf.saved_model.signature_constants.PREDICT_OUTPUTS + +# Parameters of the palette search index. +EMBEDDING_DIMENSION = 15 +NUM_ANNOY_TREES = 10 + +# Some beautiful 5-color palettes. Each palette string contains 5 RGB colors +# encoded as hexadecimal strings. View the palettes at +# https://artsexperiments.withgoogle.com/artpalette/colors/ +# where is a palette string. +SAMPLE_PALETTES = ( + '85837c-d2d1d0-9b7360-e4e3e2-b5ab98', + '91928f-204034-a3a7a5-799b7c-3b6b58', + '989b92-5a5a35-484826-495a42-957253', + '6e7b54-ededab-484826-495a42-5e4127', + '747e55-97a377-2c3933-516753-724639', + 'ffffff-d3cac1-ded5cb-171512-100d0a', + '0f1211-a1b0b3-505c5d-2e3739-6b7e86', + '17171b-edd97a-58585e-3f3e47-696768', + '221e22-c9b5a0-28374c-324258-9c836f', + '1a1e20-5b6457-978758-333e39-a4937c', + '774d3d-5b6065-8d7357-a59289-4d423b', + '818788-78371b-3a2c2b-9b8574-565959', + '171511-2e3117-a2947f-653c22-3c4911', + 'a8a28e-282313-53482b-8a6d45-787f7a', + '21181a-8e5d35-9e371f-5c3629-c3a07e', + '9e724f-33473f-a44328-28335a-453033', + '28292d-39504a-a09268-69473c-2d383c', + '314435-b27817-455266-9a3c34-bb9e82', + '283130-a05b3b-33745e-52382f-988d7a', + '213b41-5d4538-477e92-c0b69e-163a60', + '9fb6bb-809daa-5b6c90-bbc5c4-4f777b', + '474961-cab65e-a16f42-5a4b3f-a49885', + '4b5b7a-c7a614-a03023-464f72-695319', + '8c7344-9e841e-919c93-3c4438-7f4815', + '644c2c-edddc6-992c2e-4b3b2d-8a693e', + 'efece5-8aa9af-d7cfbc-5c828c-b9a47e', + 'daae2f-b3a886-b45b1e-745136-c3b05c', + '342b29-b6996f-5e5743-214440-82462b', + '947c3c-6f6747-4c3f27-b79f55-879e88', + 'e8e1c8-b79173-bbb69d-f6f3e8-84866d', + 'c1cebd-f9e37c-fbf3dd-f8e8aa-e4e2cf', + 'bea67a-3c5143-d4d2bd-ad7f42-858e81', + '9c9a95-555864-c2c2bf-b59e70-7e6844', +) + + +def RgbFromHex(color_hex): + """Returns a RGB color from a color hex. + + Args: + color_hex: A string encoding a single color. Example: '8f7358'. + + Returns: + A RGB color i.e. a 3-int tuple. Example: (143, 115, 88). + """ + return tuple(int(color_hex[i:i + 2], 16) for i in (0, 2, 4)) + + +def GetPaletteFromString(palette_string): + """Converts a string to a RGB color palette. + + Args: + palette_string: A string encoding a color palette with color hexes. The + expected format is 'color1-color2-color3-color4-color5' with colors + encoded as hex strings. Example: '8f7358-8e463d-d4d1cc-26211f-f2f0f3'. + + Returns: + A RGB color palette i.e. a list of RGB colors. + """ + return [RgbFromHex(color_hex) for color_hex in palette_string.split('-')] + + +def ConvertPalettesToLab(rgb_palettes): + """Converts a list of RGB color palettes to the Lab color space. + + Args: + rgb_palettes: A list of RGB palettes. + + Returns: + A list of Lab palettes. Lab palettes are a list of Lab colors i.e. a list of + 3-int tuples + """ + scaled_palettes = np.array(rgb_palettes) / 255.0 + return color.rgb2lab(scaled_palettes) + + +class PaletteEmbeddingModel(object): + """Runs a palette embedding model. + + The Euclidean distance between two palette embeddings is a perceptual distance + between the original palettes. Supports only 5-color palettes. Will produce + 15-dimensional dense embeddings. + + Attributes: + _sess: A Tensorflow session running the embedding model. + _in_tensor: The input tensor of the model. Should be fed a Lab color + palette. + _out_tensor: The output tensor of the model. Will contain the palette + embedding. + """ + + def __init__(self): + """Inits PaletteEmbeddingModel with the demo saved model.""" + self._sess = tf.Session(graph=tf.Graph()) + meta_graph_def = tf.saved_model.loader.load(self._sess, [TAG], MODEL_DIR) + signature = meta_graph_def.signature_def + in_tensor_name = signature[SIGNATURE_KEY].inputs[IN_TENSOR_KEY].name + out_tensor_name = signature[SIGNATURE_KEY].outputs[OUT_TENSOR_KEY].name + self._in_tensor = self._sess.graph.get_tensor_by_name(in_tensor_name) + self._out_tensor = self._sess.graph.get_tensor_by_name(out_tensor_name) + + def BatchEmbed(self, palettes): + """Returns the embedding of a list of color palettes. + + Args: + palettes: A list of strings each representing a 5-color palette. + + Returns: + A list of 15-D numpy arrays. The size of the list is equal to the size of + the input palette list. + """ + rgb_palettes = [GetPaletteFromString(palette) for palette in palettes] + lab_palettes = ConvertPalettesToLab(rgb_palettes) + in_tensors = [lab_palette.flatten() for lab_palette in lab_palettes] + return self._sess.run(self._out_tensor, {self._in_tensor: in_tensors}) + + def Embed(self, palette): + """Returns the embedding of a single color palette. + + Args: + palette: A string representing a 5-color palette. + + Returns: + A 15-D numpy array. + """ + return self.BatchEmbed([palette])[0] + + def ComputeDistance(self, a, b): + """Returns a perceptual distance between two palettes. + + Args: + a: A palette (string). + b: Another palette (string). + + Returns: + The distance between the palettes as a float. + """ + embeddings = self.BatchEmbed([a, b]) + return np.linalg.norm(embeddings[0] - embeddings[1]) + + +class PaletteSearchIndex(object): + """Data structure for nearest-neighbor search in color palette space. + + Attributes: + _embedding_model: PaletteEmbeddingModel. + _index: annoy.AnnoyIndex. + """ + + def __init__(self, embedding_model, palettes): + """Inits PaletteSearchIndex with a list of color palettes. + + The palette index will compute the nearest neighbors in the input palette + list. + + Args: + embedding_model: PaletteEmbeddingModel. The embedding model to use. + palettes: A list of strings each representing a 5-color palette. + """ + self._embedding_model = embedding_model + embeddings = self._embedding_model.BatchEmbed(palettes) + self._index = annoy.AnnoyIndex(EMBEDDING_DIMENSION, metric='euclidean') + for i, embedding in enumerate(embeddings): + self._index.add_item(i, embedding) + self._index.build(NUM_ANNOY_TREES) + + def GetNearestNeighbors(self, palette, num_neighbors): + """Return the nearest neighbors of the input palette. + + Will return the index of the nearest palettes in the palette list that was + used to initialize the PaletteSearchIndex. + + Args: + palette: A string representing a color palette. + num_neighbors: The number of neighbors to return. + + Returns: + A pair of lists. The first list contains the indices of the neighbors. The + second one contains the distances to the neighbors. Both list are sorted + by neighbor distance. + """ + embedding = self._embedding_model.Embed(palette) + return self._index.get_nns_by_vector( + embedding, num_neighbors, include_distances=True) + + +def main(): + print '======================' + print 'Palette embedding demo' + print '======================' + print + + # Load the embedding model + model = PaletteEmbeddingModel() + + # Compute an abstract embedding of some sample palettes. + embeddings = model.BatchEmbed(SAMPLE_PALETTES) + print "Embedding of palette '{}' is {}\n".format(SAMPLE_PALETTES[0], + embeddings[0]) + + # The embedding provides a perceptual distance between palettes. + sample_distance = model.ComputeDistance(SAMPLE_PALETTES[0], + SAMPLE_PALETTES[1]) + print "Distance between palette '{}' and '{}' is {}\n".format( + SAMPLE_PALETTES[0], SAMPLE_PALETTES[1], sample_distance) + + # Create an palette search index. + palette_index = PaletteSearchIndex(model, SAMPLE_PALETTES) + + # Search for the nearest neighbors of a palette. + palette_query = 'aaaa8f-282313-53482b-8a6d45-787f7a' + num_neighbors = 10 + indices, distances = palette_index.GetNearestNeighbors( + palette_query, num_neighbors) + print "The {} nearest neighbor(s) of palette '{}' are:".format( + num_neighbors, palette_query) + for index, distance in zip(indices, distances): + print "'{0}': {1:.2f}".format(SAMPLE_PALETTES[index], distance) + + +if __name__ == '__main__': + main() + diff --git a/palette-extraction/README.md b/palette-extraction/README.md new file mode 100644 index 0000000..2f8c981 --- /dev/null +++ b/palette-extraction/README.md @@ -0,0 +1,16 @@ +# Palette Extractor + +![Palette Extractor](palette_demo_example.jpg?raw=true) + +The javascript palette extractor returns the palette calculated for an [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData). + +The implementation is largely based on [Palette-Based Photo Recoloring (Chang and al. 2015)](http://gfx.cs.princeton.edu/pubs/Chang_2015_PPR/chang2015-palette_small.pdf), section 3.2. + +## Using the library + +Draw your image in a canvas and get the `ImageData.data` [Uint8ClampedArray](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) that represents a one-dimensional array containing the data in the RGBA order, with integer values between 0 and 255 (included), using *getImageData*. +Use that data to get the hexadecimal colors palette by simply calling *processImageData* with the expected palette colors count: +``` +const data = canvasContext.getImageData(0, 0, canvas.width, canvas.height).data; +const hexPalette = paletteExtractor.processImageData(data, 5); +``` diff --git a/palette-extraction/index.html b/palette-extraction/index.html new file mode 100644 index 0000000..a3bc3b6 --- /dev/null +++ b/palette-extraction/index.html @@ -0,0 +1,126 @@ + + + + + Art Palette + + + + + +

Colors Palette Extractor

+ +
    + + + + + diff --git a/palette-extraction/palette_demo_example.jpg b/palette-extraction/palette_demo_example.jpg new file mode 100644 index 0000000..d8b144e Binary files /dev/null and b/palette-extraction/palette_demo_example.jpg differ diff --git a/palette-extraction/palette_extractor.min.js b/palette-extraction/palette_extractor.min.js new file mode 100755 index 0000000..063f699 --- /dev/null +++ b/palette-extraction/palette_extractor.min.js @@ -0,0 +1,16 @@ +/* +Copyright 2018 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const arrayUtils={clone:function(d){var e=d.length;if(0e&&(e=d[h],f=h);return f}addColorToSeed_(d,e,f){e in d||(d[e]=vec3Utils.createFloat32FromArray([0,0,0])),vec3Utils.add(d[e],this.labs_[f],d[e]),this.seedWeights_[e]+=this.weights_[f]}updateSeedsWithNewSeeds_(d){for(let e=0;e|string} arr Array or array-like object to clone. + * @return {!Array} Clone of the input array. + */ +arrayUtils.clone = function(arr) { + var length = arr.length; + if (length > 0) { + var rv = new Array(length); + for (var i = 0; i < length; i++) { + rv[i] = arr[i]; + } + return rv; + } + return []; +}; + +/** + * Returns an array consisting of the given value repeated N times. + * @param {VALUE} value The value to repeat. + * @param {number} n The repeat count. + * @return {!Array} An array with the repeated value. + */ +arrayUtils.repeat = function(value, n) { + var array = []; + for (var i = 0; i < n; i++) { + array[i] = value; + } + return array; +}; diff --git a/palette-extraction/src/palette_extractor.js b/palette-extraction/src/palette_extractor.js new file mode 100644 index 0000000..1f79140 --- /dev/null +++ b/palette-extraction/src/palette_extractor.js @@ -0,0 +1,520 @@ +/* +Copyright 2018 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +/** + * @fileoverview Provides an api to get a palette from image pixel data + * The implementation is largely based on Palette-Based Photo Recoloring [Chang + * et al. 2015], section 3.2. + * + * Here are the main steps to generate a palette from RGB data: + * 1. Accumulate RGB data (from an image for instance) in a 16x16x16 RGB + * histogram. + * 2. Keep track of the average Lab color of every histogram bin. + * 3. Run K-means on these 4096 Lab colors to create clusters. + * 4. Create a color palette using the mean colors defined by each cluster. + */ + +class PaletteExtractor { + constructor() { + /** + * Histogram bins containing lab values. + * @private {!Array} + */ + this.labs_ = []; + + /** + * Weights values for each lab. + * @private {!Array} + */ + this.weights_ = []; + + /** + * Seeds selected from the histogram. + * @private {!Array} + */ + this.seeds_ = []; + + /** + * Weights values for each seed. + * @private {!Array} + */ + this.seedWeights_ = []; + } + + /** + * Starts the process to generate a palette from RGB data. + * @param {!Array} data pixels colors - extracted from images using + * canvasContext.getImageData + * @param {number=} paletteSize (Optional) max number of color to get in + * palette (5 if not set) + * @return {!Array} hexadecimal colors + * @package + */ + processImageData(data, paletteSize = 5) { + this.computeHistogramFromImageData_(data); + this.selectSeeds_(paletteSize); + this.clusterColors_(); + return this.exportPalette_(); + } + + /** + * Computes histogram from image data (step 1). + * @param {!Array} data + * @private + */ + computeHistogramFromImageData_(data) { + const l = data.length; + // reset histogram + this.labs_ = []; + this.weights_ = arrayUtils.repeat(0, PaletteExtractor.HISTOGRAM_SIZE_); + + for (let i = 0; i < l; i += 4) { + const r = data[i], g = data[i + 1], b = data[i + 2]; + // Convert RGB color to Lab. + const lab = vec3Utils.createFloat32FromArray(this.rgbToLab(r, g, b)); + // Get the index of the corresponding histogram bin. + const index = (Math.floor(r / 16) * 16 + Math.floor(g / 16)) * 16 + + Math.floor(b / 16); + // Add the Lab color to the associated bin. + if (!(index in this.labs_)) { + this.labs_[index] = lab; + } else { + vec3Utils.add(this.labs_[index], lab, this.labs_[index]); + } + // Keep track of the number of colors added to every bin. + this.weights_[index]++; + } + } + + /** + * Selects seeds in current histogram (step 2). + * @param {number} nbSeeds + * @private + */ + selectSeeds_(nbSeeds) { + // Reset histogram + this.seeds_ = []; + // Local copy of the weight bins to edit during seed selection. + const mutableWeights = arrayUtils.clone(this.weights_); + + // Iteratively selects seeds as the heaviest bins in mutableWeights. + // After selecting a seed, attenuates neighboring bin weights to increase + // color variance. + let seedColor; + let maxIndex = 0; + for (let i = 0; i < nbSeeds; ++i) { + // Get the index of the heaviest bin. + maxIndex = this.getHeaviestIndex_(mutableWeights); + + // Check that the selected bin is not empty. + // Otherwise, it means that the previous seeds already cover all + // non-empty bins. + if (mutableWeights[maxIndex] == 0) { + break; + } + + // Set the new seed as the heaviest bin. + seedColor = this.addSeedByIndex_(maxIndex); + + // Force the next seed to be different (unless all bin weights are 0). + mutableWeights[maxIndex] = 0; + + // Attenuate weights close to the seed to maximize distance between seeds. + this.attenuateWeightsAroundSeed_(mutableWeights, seedColor); + } + } + + /** + * Runs K-means on histogram from seeds to create clusters (step 3). + * @private + */ + clusterColors_() { + if (!this.seeds_.length) { + throw Error('Please select seeds before clustering'); + } + + const clusterIndices = arrayUtils.repeat(0, PaletteExtractor.HISTOGRAM_SIZE_); + let newSeeds = []; + this.seedWeights_ = []; + let optimumReached = false; + let i = 0; + while (!optimumReached) { + optimumReached = true; + newSeeds = []; + this.seedWeights_ = arrayUtils.repeat(0, this.seeds_.length); + // Assign every bin of the color histogram to the closest seed. + for (i = 0; i < PaletteExtractor.HISTOGRAM_SIZE_; i++) { + if (this.weights_[i] == 0) continue; + + // Compute the index of the seed that is closest to the bin's color. + const clusterIndex = this.getClosestSeedIndex_(i); + // Optimum is reached when no cluster assignment changes. + if (optimumReached && clusterIndex != clusterIndices[i]) { + optimumReached = false; + } + // Assign bin to closest seed. + clusterIndices[i] = clusterIndex; + // Accumulate colors and weights per cluster. + this.addColorToSeed_(newSeeds, clusterIndex, i); + } + // Average accumulated colors to get new seeds. + this.updateSeedsWithNewSeeds_(newSeeds); + } + } + + /** + * Exports palette as hexadecimal colors array from current seeds list (step + * 4). + * @return {!Array} hexadecimal colors + * @private + */ + exportPalette_() { + if (!this.seeds_.length) { + throw Error( + 'Please select seeds and get clusters ' + + 'before exporting a new palette'); + } + + const results = []; + + for (let i = 0; i < this.seeds_.length; i++) { + const rgb = this.labToRgb( + this.seeds_[i][0], this.seeds_[i][1], this.seeds_[i][2]); + results.push(this.rgbToHex(rgb[0], rgb[1], rgb[2])); + } + + return results; + } + + /** + * Attenuates weights close to the seed to maximize distance between seeds. + * @param {!Array} mutableWeights + * @param {!Float32Array} seedColor + * @private + */ + attenuateWeightsAroundSeed_(mutableWeights, seedColor) { + // For photos, we can use a higher coefficient, from 900 to 6400 + const squaredSeparationCoefficient = 3650; + + for (let i = 0; i < PaletteExtractor.HISTOGRAM_SIZE_; i++) { + if (this.weights_[i] > 0) { + const targetColor = vec3Utils.createFloat32FromArray([0, 0, 0]); + vec3Utils.scale(this.labs_[i], 1 / this.weights_[i], targetColor); + mutableWeights[i] *= 1 - + Math.exp( + -vec3Utils.distanceSquared(seedColor, targetColor) / + squaredSeparationCoefficient); + } + } + } + + /** + * Pushes a color from the histogram to the seeds list. + * @param {number} index + * @return {!Float32Array} seedColor + * @private + */ + addSeedByIndex_(index) { + const seedColor = vec3Utils.createFloat32FromArray([0, 0, 0]); + vec3Utils.scale(this.labs_[index], 1 / this.weights_[index], seedColor); + this.seeds_.push(seedColor); + return seedColor; + } + + /** + * Gets heaviest index. + * @param {!Array} weights + * @return {number} index + * @private + */ + getHeaviestIndex_(weights) { + let heaviest = 0; + let index = 0; + for (let m = 0; m < PaletteExtractor.HISTOGRAM_SIZE_; m++) { + if (weights[m] > heaviest) { + heaviest = weights[m]; + index = m; + } + } + return index; + } + + /** + * Accumulates colors and weights per cluster. + * @param {!Array} seeds + * @param {number} clusterIndex + * @param {number} histogramIndex + * @private + */ + addColorToSeed_(seeds, clusterIndex, histogramIndex) { + if (!(clusterIndex in seeds)) { + seeds[clusterIndex] = vec3Utils.createFloat32FromArray([0, 0, 0]); + } + vec3Utils.add( + seeds[clusterIndex], this.labs_[histogramIndex], seeds[clusterIndex]); + this.seedWeights_[clusterIndex] += this.weights_[histogramIndex]; + } + + /** + * Updates seeds with average colors using new seed values and seed weights. + * @param {!Array} newSeeds + * @private + */ + updateSeedsWithNewSeeds_(newSeeds) { + for (let i = 0; i < this.seeds_.length; i++) { + if (!(i in newSeeds)) { + newSeeds[i] = vec3Utils.createFloat32FromArray([0, 0, 0]); + } + + if (this.seedWeights_[i] == 0) { + newSeeds[i] = vec3Utils.createFloat32FromArray([0, 0, 0]); + } else { + vec3Utils.scale(newSeeds[i], 1 / this.seedWeights_[i], newSeeds[i]); + } + + // Update seeds. + this.seeds_[i] = vec3Utils.cloneFloat32(newSeeds[i]); + } + } + + /** + * Gets the closest seed index for a color in the histogram. + * @param {number} index in histogram + * @return {number} seed index + * @private + */ + getClosestSeedIndex_(index) { + const color = vec3Utils.cloneFloat32(this.labs_[index]); + vec3Utils.scale(color, 1 / this.weights_[index], color); + let seedDistMin = Number.MAX_SAFE_INTEGER; + let seedIndex = 0; + for (let i = 0; i < this.seeds_.length; i++) { + const dist = vec3Utils.distanceSquared(this.seeds_[i], color); + if (dist < seedDistMin) { + seedDistMin = dist; + seedIndex = i; + } + } + return seedIndex; + }; + + /** + * Converts color component to hexaminal part. + * @param {number} c Component color value (r,g or b) + * @return {string} The hexadecimal converted part + * @package + */ + componentToHex(c) { + var hex = c.toString(16); + return hex.length == 1 ? '0' + hex : hex; + }; + + /** + * Converts a color from RGB to hex representation. + * @param {number} r Amount of red, int between 0 and 255. + * @param {number} g Amount of green, int between 0 and 255. + * @param {number} b Amount of blue, int between 0 and 255. + * @return {string} hex representation of the color. + */ + rgbToHex(r, g, b) { + r = Number(r); + g = Number(g); + b = Number(b); + if (r != (r & 255) || g != (g & 255) || b != (b & 255)) { + throw Error('"(' + r + ',' + g + ',' + b + '") is not a valid RGB color'); + } + const hexR = this.componentToHex(r); + const hexG = this.componentToHex(g); + const hexB = this.componentToHex(b); + return '#' + hexR + hexG + hexB; + }; + + /** + * Converts RGB color values to LAB. + * @param {!number} r The R value of the color. + * @param {!number} g The G value of the color. + * @param {!number} b The B value of the color. + * @return {!Array} An array of LAB values in that order. + */ + rgbToLab(r, g, b) { + r = r / 255.0; + g = g / 255.0; + b = b / 255.0; + const xyz = this.rgbToXyz(r, g, b); + return this.xyzToLab(xyz[0], xyz[1], xyz[2]); + } + + /** + * Converts LAB color values to RGB. + * @param {!number} lValue The L value of the color. + * @param {!number} a The A value of the color. + * @param {!number} b The B value of the color. + * @return {!Array} An array of RGB values in that order. + */ + labToRgb(lValue, a, b) { + const xyz = this.labToXyz(lValue, a, b); + const rgb = this.xyzToRgb(xyz[0], xyz[1], xyz[2]); + return [ + Math.min(255, Math.max(0, Math.round(rgb[0] * 255))), + Math.min(255, Math.max(0, Math.round(rgb[1] * 255))), + Math.min(255, Math.max(0, Math.round(rgb[2] * 255))) + ]; + } + + /** + * Converts XYZ color values to RGB. + * Formula for conversion found at: + * http://www.easyrgb.com/index.php?X=MATH&H=01#text1 + * @param {!number} x The X value of the color. + * @param {!number} y The Y value of the color. + * @param {!number} z The Z value of the color. + * @return {!Array} An array of RGB values in that order. + */ + xyzToRgb(x, y, z) { + x = x / 100.0; + y = y / 100.0; + z = z / 100.0; + let r = x * 3.2406 + y * -1.5372 + z * -0.4986; + let g = x * -0.9689 + y * 1.8758 + z * 0.0415; + let b = x * 0.0557 + y * -0.2040 + z * 1.0570; + if (r > 0.0031308) { + r = 1.055 * Math.pow(r, 1 / 2.4) - .055; + } else { + r = 12.92 * r; + } + if (g > 0.0031308) { + g = 1.055 * Math.pow(g, 1 / 2.4) - .055; + } else { + g = 12.92 * g; + } + if (b > 0.0031308) { + b = 1.055 * Math.pow(b, 1 / 2.4) - .055; + } else { + b = 12.92 * b; + } + return [r, g, b]; + } + + /** + * Converts LAB color values to XYZ. + * Formula for conversion found at: + * http://www.easyrgb.com/index.php?X=MATH&H=08#text8 + * @param {!number} lValue The L value of the color. + * @param {!number} a The A value of the color. + * @param {!number} b The B value of the color. + * @return {!Array} An array of XYZ values in that order. + */ + labToXyz(lValue, a, b) { + const p = (lValue + 16) / 116; + return [ + PaletteExtractor.REF_X * Math.pow(p + a / 500, 3), + PaletteExtractor.REF_Y * Math.pow(p, 3), + PaletteExtractor.REF_Z * Math.pow(p - b / 200, 3) + ]; + } + + /** + * Converts XYZ color values to LAB. + * Formula for conversion found at: + * http://www.easyrgb.com/index.php?X=MATH&H=07#text7 + * @param {!number} x The X value of the color. + * @param {!number} y The Y value of the color. + * @param {!number} z The Z value of the color. + * @return {!Array} An array of LAB values in that order. + */ + xyzToLab(x, y, z) { + const xRatio = x / PaletteExtractor.REF_X; + const yRatio = y / PaletteExtractor.REF_Y; + const zRatio = z / PaletteExtractor.REF_Z; + return [ + yRatio > 0.008856 ? 116 * Math.pow(yRatio, 1.0 / 3) - 16 : 903.3 * yRatio, + 500 * (this.transformation(xRatio) - this.transformation(yRatio)), + 200 * (this.transformation(yRatio) - this.transformation(zRatio)) + ]; + } + + /** + * Converts RGB color values to XYZ. + * Formula for conversion found at: + * http://www.easyrgb.com/index.php?X=MATH&H=02#text2 + * @param {!number} r The R value of the color. + * @param {!number} g The G value of the color. + * @param {!number} b The B value of the color. + * @return {!Array} An array of XYZ values in that order. + */ + rgbToXyz(r, g, b) { + if (r > 0.04045) { + r = Math.pow((r + .055) / 1.055, 2.4); + } else { + r = r / 12.92; + } + if (g > 0.04045) { + g = Math.pow((g + .055) / 1.055, 2.4); + } else { + g = g / 12.92; + } + if (b > 0.04045) { + b = Math.pow((b + .055) / 1.055, 2.4); + } else { + b = b / 12.92; + } + r = r * 100; + g = g * 100; + b = b * 100; + return [ + r * 0.4124 + g * 0.3576 + b * 0.1805, + r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505 + ]; + } + + /** + * Transformation function for CIELAB-CIEXYZ conversion. For more info, please + * see http://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions + * @param {!number} t An input to the transformation function. + * @return {!number} The transformed value. + */ + transformation(t) { + if (t > 0.008856) { + return Math.pow(t, 1.0 / 3); + } + return 7.787 * t + 16.0 / 116; + } +} + +/** + * Total number of cells in the histogram. + * @private @const @type {number} + */ +PaletteExtractor.HISTOGRAM_SIZE_ = 4096; + +/** + * Reference values for Illuminant D65, a reference for color conversion. + * @const @type {!number} + */ +PaletteExtractor.REF_X = 95.047; + +/** + * @const @type {!number} + */ +PaletteExtractor.REF_Y = 100; + +/** + * @const @type {!number} + */ +PaletteExtractor.REF_Z = 108.883; + + +exports = PaletteExtractor; diff --git a/palette-extraction/src/palette_vec3_utils.js b/palette-extraction/src/palette_vec3_utils.js new file mode 100644 index 0000000..90afdea --- /dev/null +++ b/palette-extraction/src/palette_vec3_utils.js @@ -0,0 +1,104 @@ +/* +Copyright 2018 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +/** + * @fileoverview A small collection of vec3 utilities. + */ + +const vec3Utils = {}; + +/** + * Performs a component-wise addition of vec0 and vec1 together storing the + * result into resultVec. + * @param {!Float32Array|!Float64Array|!Array} vec0 The first addend. + * @param {!Float32Array|!Float64Array|!Array} vec1 The second addend. + * @param {!Float32Array|!Float64Array|!Array} resultVec The vector to + * receive the result. May be vec0 or vec1. + * @return {!Float32Array|!Float64Array|!Array} Return resultVec + * so that operations can be chained together. + */ +vec3Utils.add = function(vec0, vec1, resultVec) { + resultVec[0] = vec0[0] + vec1[0]; + resultVec[1] = vec0[1] + vec1[1]; + resultVec[2] = vec0[2] + vec1[2]; + return resultVec; +}; + +/** + * Multiplies each component of vec0 with scalar storing the product into + * resultVec. + * @param {!Float32Array|!Float64Array|!Array} vec0 The source vector. + * @param {number} scalar The value to multiply with each component of vec0. + * @param {!Float32Array|!Float64Array|!Array} resultVec The vector to + * receive the result. May be vec0. + * @return {!Float32Array|!Float64Array|!Array} Return resultVec + * so that operations can be chained together. + */ +vec3Utils.scale = function(vec0, scalar, resultVec) { + resultVec[0] = vec0[0] * scalar; + resultVec[1] = vec0[1] * scalar; + resultVec[2] = vec0[2] * scalar; + return resultVec; +}; + +/** + * Returns the squared distance between two points. + * @param {!Float32Array|!Float64Array|!Array} vec0 First point. + * @param {!Float32Array|!Float64Array|!Array} vec1 Second point. + * @return {number} The squared distance between the points. + */ +vec3Utils.distanceSquared = function(vec0, vec1) { + var x = vec0[0] - vec1[0]; + var y = vec0[1] - vec1[1]; + var z = vec0[2] - vec1[2]; + return x * x + y * y + z * z; +}; + +/** + * Initializes the vector with the given array of values. + * @param {!Float32Array|!Float64Array|!Array} vec The vector + * to receive the values. + * @param {!Float32Array|!Float64Array|!Array} values The array + * of values. + * @return {!Float32Array|!Float64Array|!Array} Return vec + * so that operations can be chained together. + */ +vec3Utils.setFromArray = function(vec, values) { + vec[0] = values[0]; + vec[1] = values[1]; + vec[2] = values[2]; + return vec; +}; + +/** + * Creates a new 3 element Float32 vector initialized with the value from the + * given array. + * @param {!Float32Array|!Float64Array|!Array} vec The source 3 element + * array. + * @return {!Float32Array} The new 3 element array. + */ +vec3Utils.createFloat32FromArray = function(vec) { + var newVec = new Float32Array(3); + vec3Utils.setFromArray(newVec, vec); + return newVec; +}; + +/** + * Creates a clone of the given 3 element Float32 vector. + * @param {!Float32Array} vec The source 3 element vector. + * @return {!Float32Array} The new cloned vector. + */ +vec3Utils.cloneFloat32 = vec3Utils.createFloat32FromArray; diff --git a/palette_example.jpg b/palette_example.jpg new file mode 100644 index 0000000..937a9b8 Binary files /dev/null and b/palette_example.jpg differ