├── .gitignore ├── LICENSE ├── LICENSE.meta ├── README.md ├── README.md.meta ├── Runtime.meta ├── Runtime ├── ColorThief.cs ├── ColorThief.cs.meta ├── Core.meta ├── Core │ ├── CMap.cs │ ├── CMap.cs.meta │ ├── Color.cs │ ├── Color.cs.meta │ ├── HslColor.cs │ ├── HslColor.cs.meta │ ├── Mmcq.cs │ ├── Mmcq.cs.meta │ ├── QuantizedColor.cs │ ├── QuantizedColor.cs.meta │ ├── SharedAssemblyInfo.cs │ ├── SharedAssemblyInfo.cs.meta │ ├── VBox.cs │ └── VBox.cs.meta ├── Lokesh.ColorThief.asmdef └── Lokesh.ColorThief.asmdef.meta ├── Samples~ ├── Demo.cs ├── Demo.cs.meta ├── Lokesh.ColorThief.Samples.asmdef └── Lokesh.ColorThief.Samples.asmdef.meta ├── package.json └── package.json.meta /.gitignore: -------------------------------------------------------------------------------- 1 | /[Ll]ibrary/ 2 | /[Tt]emp/ 3 | /[Oo]bj/ 4 | /[Bb]uild/ 5 | /[Bb]uilds/ 6 | /Assets/AssetStoreTools* 7 | 8 | # Visual Studio 2015 cache directory 9 | /.vs/ 10 | 11 | # Autogenerated VS/MD/Consulo solution and project files 12 | ExportedObj/ 13 | .consulo/ 14 | *.csproj 15 | *.unityproj 16 | *.sln 17 | *.suo 18 | *.tmp 19 | *.user 20 | *.userprefs 21 | *.pidb 22 | *.booproj 23 | *.svd 24 | *.pdb 25 | 26 | # Unity3D generated meta files 27 | *.pidb.meta 28 | 29 | # Unity3D Generated File On Crash Reports 30 | sysinfo.txt 31 | 32 | # Builds 33 | *.apk 34 | *.unitypackage 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 CHIU TSE 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | 24 | 25 | The MIT License (MIT) 26 | 27 | Copyright (c) 2015 Lokesh Dhakar 28 | 29 | Permission is hereby granted, free of charge, to any person obtaining a copy 30 | of this software and associated documentation files (the "Software"), to deal 31 | in the Software without restriction, including without limitation the rights 32 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 33 | copies of the Software, and to permit persons to whom the Software is 34 | furnished to do so, subject to the following conditions: 35 | 36 | The above copyright notice and this permission notice shall be included in all 37 | copies or substantial portions of the Software. 38 | 39 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 40 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 41 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 42 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 43 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 44 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 45 | SOFTWARE. -------------------------------------------------------------------------------- /LICENSE.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e052c479e249cdf44bda07e4fcc94177 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Color Thief Unity 2 | A code for grabbing the color palette from an image. 3 | 4 | Original Project [Color Thief](https://github.com/lokesh/color-thief) by lokesh 5 | Ported Project of [Color Thief .NET](https://github.com/KSemenenko/ColorThief) by KSemenenko 6 | [Unity Version](https://github.com/chiutse/ColorThief) by chiutse 7 | [Unity Package Manager version](https://github.com/needle-tools/ColorThief.git) by hybridherbst 8 | 9 | ## How To Use 10 | Dominant Color 11 | ```cs 12 | var dominant = new ColorThief.ColorThief(); 13 | Color color = dominant.GetColor(texture).UnityColor; 14 | ``` 15 | 16 | Palette Color 17 | ```cs 18 | var palette = new ColorThief.ColorThief(); 19 | List colors = palette.GetPalette(texture, paletteColors.Length); 20 | ``` 21 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3dd3888df53b89742b5da87c1e0b2456 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6db25f7e9351365468e6ecfc92bb021c 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/ColorThief.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | // using System.Drawing; 4 | using System.Linq; 5 | using UnityEngine; 6 | 7 | namespace ColorThief 8 | { 9 | public class ColorThief 10 | { 11 | private const int DefaultColorCount = 5; 12 | private const int DefaultQuality = 10; 13 | private const bool DefaultIgnoreWhite = true; 14 | 15 | /// 16 | /// Use the median cut algorithm to cluster similar colors and return the base color from the largest cluster. 17 | /// 18 | /// The source image. 19 | /// 20 | /// 0 is the highest quality settings. 10 is the default. There is 21 | /// a trade-off between quality and speed. The bigger the number, 22 | /// the faster a color will be returned but the greater the 23 | /// likelihood that it will not be the visually most dominant color. 24 | /// 25 | /// if set to true [ignore white]. 26 | /// 27 | public QuantizedColor GetColor(Texture2D sourceImage, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) 28 | { 29 | var palette = GetPalette(sourceImage, DefaultColorCount, quality, ignoreWhite); 30 | var dominantColor = palette.FirstOrDefault(); 31 | return dominantColor; 32 | } 33 | 34 | /// 35 | /// Use the median cut algorithm to cluster similar colors. 36 | /// 37 | /// The source image. 38 | /// The color count. 39 | /// 40 | /// 0 is the highest quality settings. 10 is the default. There is 41 | /// a trade-off between quality and speed. The bigger the number, 42 | /// the faster a color will be returned but the greater the 43 | /// likelihood that it will not be the visually most dominant color. 44 | /// 45 | /// if set to true [ignore white]. 46 | /// 47 | /// true 48 | public List GetPalette(Texture2D sourceImage, int colorCount = DefaultColorCount, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) 49 | { 50 | var cmap = GetColorMap(sourceImage, colorCount, quality, ignoreWhite); 51 | return cmap != null ? cmap.GeneratePalette() : new List(); 52 | } 53 | 54 | /// 55 | /// Use the median cut algorithm to cluster similar colors. 56 | /// 57 | /// The source image. 58 | /// The color count. 59 | /// 60 | /// 0 is the highest quality settings. 10 is the default. There is 61 | /// a trade-off between quality and speed. The bigger the number, 62 | /// the faster a color will be returned but the greater the 63 | /// likelihood that it will not be the visually most dominant color. 64 | /// 65 | /// if set to true [ignore white]. 66 | /// 67 | private CMap GetColorMap(Texture2D sourceImage, int colorCount, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) 68 | { 69 | var pixelArray = GetPixelsFast(sourceImage, quality, ignoreWhite); 70 | 71 | // Send array to quantize function which clusters values using median 72 | // cut algorithm 73 | var cmap = Mmcq.Quantize(pixelArray, colorCount); 74 | return cmap; 75 | } 76 | 77 | private IEnumerable GetIntFromPixel(Texture2D bmp) 78 | { 79 | Color32[] clrs = bmp.GetPixels32(); 80 | for(int i=0; i= 125 && !(ignoreWhite && r > 250 && g > 250 && b > 250)) 138 | { 139 | pixelArray[numUsedPixels] = new[] {r, g, b}; 140 | numUsedPixels++; 141 | } 142 | } 143 | 144 | // Remove unused pixels from the array 145 | var copy = new int[numUsedPixels][]; 146 | Array.Copy(pixelArray, copy, numUsedPixels); 147 | return copy; 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /Runtime/ColorThief.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 5e6baea82a6b8af438bae20cace80dce 3 | timeCreated: 1512377248 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3738d5a04d2353c45955f6e4273420d8 3 | folderAsset: yes 4 | timeCreated: 1512098114 5 | licenseType: Free 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Runtime/Core/CMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace ColorThief 6 | { 7 | /// 8 | /// Color map 9 | /// 10 | internal class CMap 11 | { 12 | private readonly List vboxes = new List(); 13 | private List palette; 14 | 15 | public void Push(VBox box) 16 | { 17 | palette = null; 18 | vboxes.Add(box); 19 | } 20 | 21 | public List GeneratePalette() 22 | { 23 | if(palette == null) 24 | { 25 | palette = (from vBox in vboxes 26 | let rgb = vBox.Avg(false) 27 | let color = FromRgb(rgb[0], rgb[1], rgb[2]) 28 | select new QuantizedColor(color, vBox.Count(false))).ToList(); 29 | } 30 | 31 | return palette; 32 | } 33 | 34 | public int Size() 35 | { 36 | return vboxes.Count; 37 | } 38 | 39 | public int[] Map(int[] color) 40 | { 41 | foreach(var vbox in vboxes.Where(vbox => vbox.Contains(color))) 42 | { 43 | return vbox.Avg(false); 44 | } 45 | return Nearest(color); 46 | } 47 | 48 | public int[] Nearest(int[] color) 49 | { 50 | var d1 = double.MaxValue; 51 | int[] pColor = null; 52 | 53 | foreach(var t in vboxes) 54 | { 55 | var vbColor = t.Avg(false); 56 | var d2 = Math.Sqrt(Math.Pow(color[0] - vbColor[0], 2) 57 | + Math.Pow(color[1] - vbColor[1], 2) 58 | + Math.Pow(color[2] - vbColor[2], 2)); 59 | if(d2 < d1) 60 | { 61 | d1 = d2; 62 | pColor = vbColor; 63 | } 64 | } 65 | return pColor; 66 | } 67 | 68 | public VBox FindColor(double targetLuma, double minLuma, double maxLuma, double targetSaturation, double minSaturation, double maxSaturation) 69 | { 70 | VBox max = null; 71 | double maxValue = 0; 72 | var highestPopulation = vboxes.Select(p => p.Count(false)).Max(); 73 | 74 | foreach(var swatch in vboxes) 75 | { 76 | var avg = swatch.Avg(false); 77 | var hsl = FromRgb(avg[0], avg[1], avg[2]).ToHsl(); 78 | var sat = hsl.S; 79 | var luma = hsl.L; 80 | 81 | if(sat >= minSaturation && sat <= maxSaturation && 82 | luma >= minLuma && luma <= maxLuma) 83 | { 84 | var thisValue = Mmcq.CreateComparisonValue(sat, targetSaturation, luma, targetLuma, 85 | swatch.Count(false), highestPopulation); 86 | 87 | if(max == null || thisValue > maxValue) 88 | { 89 | max = swatch; 90 | maxValue = thisValue; 91 | } 92 | } 93 | } 94 | 95 | return max; 96 | } 97 | 98 | public Color FromRgb(int red, int green, int blue) 99 | { 100 | var color = new Color 101 | { 102 | A = 255, 103 | R = (byte)red, 104 | G = (byte)green, 105 | B = (byte)blue 106 | }; 107 | 108 | return color; 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /Runtime/Core/CMap.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 67ab796fc5cb90f49a28fc97fd3680df 3 | timeCreated: 1512098117 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/Color.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ColorThief 4 | { 5 | /// 6 | /// Defines a color in RGB space. 7 | /// 8 | public struct Color 9 | { 10 | /// 11 | /// Get or Set the Alpha component value for sRGB. 12 | /// 13 | public byte A; 14 | 15 | /// 16 | /// Get or Set the Blue component value for sRGB. 17 | /// 18 | public byte B; 19 | 20 | /// 21 | /// Get or Set the Green component value for sRGB. 22 | /// 23 | public byte G; 24 | 25 | /// 26 | /// Get or Set the Red component value for sRGB. 27 | /// 28 | public byte R; 29 | 30 | /// 31 | /// Get HSL color. 32 | /// 33 | /// 34 | public HslColor ToHsl() 35 | { 36 | const double toDouble = 1.0 / 255; 37 | var r = toDouble * R; 38 | var g = toDouble * G; 39 | var b = toDouble * B; 40 | var max = Math.Max(Math.Max(r, g), b); 41 | var min = Math.Min(Math.Min(r, g), b); 42 | var chroma = max - min; 43 | double h1; 44 | 45 | // ReSharper disable CompareOfFloatsByEqualityOperator 46 | if(chroma == 0) 47 | { 48 | h1 = 0; 49 | } 50 | else if(max == r) 51 | { 52 | h1 = (g - b) / chroma % 6; 53 | } 54 | else if(max == g) 55 | { 56 | h1 = 2 + (b - r) / chroma; 57 | } 58 | else //if (max == b) 59 | { 60 | h1 = 4 + (r - g) / chroma; 61 | } 62 | 63 | var lightness = 0.5 * (max - min); 64 | var saturation = chroma == 0 ? 0 : chroma / (1 - Math.Abs(2 * lightness - 1)); 65 | HslColor ret; 66 | ret.H = 60 * h1; 67 | ret.S = saturation; 68 | ret.L = lightness; 69 | ret.A = toDouble * A; 70 | return ret; 71 | // ReSharper restore CompareOfFloatsByEqualityOperator 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /Runtime/Core/Color.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cadd0185abfa88140a695c173f4f1008 3 | timeCreated: 1512098118 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/HslColor.cs: -------------------------------------------------------------------------------- 1 | namespace ColorThief 2 | { 3 | /// 4 | /// Defines a color in Hue/Saturation/Lightness (HSL) space. 5 | /// 6 | public struct HslColor 7 | { 8 | /// 9 | /// The Alpha/opacity in 0..1 range. 10 | /// 11 | public double A; 12 | 13 | /// 14 | /// The Hue in 0..360 range. 15 | /// 16 | public double H; 17 | 18 | /// 19 | /// The Lightness in 0..1 range. 20 | /// 21 | public double L; 22 | 23 | /// 24 | /// The Saturation in 0..1 range. 25 | /// 26 | public double S; 27 | } 28 | } -------------------------------------------------------------------------------- /Runtime/Core/HslColor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 8d191a443f698de4ba65dbb8c6fc4289 3 | timeCreated: 1512098117 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/Mmcq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace ColorThief 5 | { 6 | internal static class Mmcq 7 | { 8 | public const int Sigbits = 5; 9 | public const int Rshift = 8 - Sigbits; 10 | public const int Mult = 1 << Rshift; 11 | public const int Histosize = 1 << (3 * Sigbits); 12 | public const int VboxLength = 1 << Sigbits; 13 | public const double FractByPopulation = 0.75; 14 | public const int MaxIterations = 1000; 15 | public const double WeightSaturation = 3d; 16 | public const double WeightLuma = 6d; 17 | public const double WeightPopulation = 1d; 18 | private static readonly VBoxComparer ComparatorProduct = new VBoxComparer(); 19 | private static readonly VBoxCountComparer ComparatorCount = new VBoxCountComparer(); 20 | 21 | public static int GetColorIndex(int r, int g, int b) 22 | { 23 | return (r << (2 * Sigbits)) + (g << Sigbits) + b; 24 | } 25 | 26 | /// 27 | /// Gets the histo. 28 | /// 29 | /// The pixels. 30 | /// Histo (1-d array, giving the number of pixels in each quantized region of color space), or null on error. 31 | private static int[] GetHisto(IEnumerable pixels) 32 | { 33 | var histo = new int[Histosize]; 34 | 35 | foreach(var pixel in pixels) 36 | { 37 | var rval = pixel[0] >> Rshift; 38 | var gval = pixel[1] >> Rshift; 39 | var bval = pixel[2] >> Rshift; 40 | var index = GetColorIndex(rval, gval, bval); 41 | histo[index]++; 42 | } 43 | return histo; 44 | } 45 | 46 | private static VBox VboxFromPixels(IList pixels, int[] histo) 47 | { 48 | int rmin = 1000000, rmax = 0; 49 | int gmin = 1000000, gmax = 0; 50 | int bmin = 1000000, bmax = 0; 51 | 52 | // find min/max 53 | var numPixels = pixels.Count; 54 | for(var i = 0; i < numPixels; i++) 55 | { 56 | var pixel = pixels[i]; 57 | var rval = pixel[0] >> Rshift; 58 | var gval = pixel[1] >> Rshift; 59 | var bval = pixel[2] >> Rshift; 60 | 61 | if(rval < rmin) 62 | { 63 | rmin = rval; 64 | } 65 | else if(rval > rmax) 66 | { 67 | rmax = rval; 68 | } 69 | 70 | if(gval < gmin) 71 | { 72 | gmin = gval; 73 | } 74 | else if(gval > gmax) 75 | { 76 | gmax = gval; 77 | } 78 | 79 | if(bval < bmin) 80 | { 81 | bmin = bval; 82 | } 83 | else if(bval > bmax) 84 | { 85 | bmax = bval; 86 | } 87 | } 88 | 89 | return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo); 90 | } 91 | 92 | private static VBox[] DoCut(char color, VBox vbox, IList partialsum, IList lookaheadsum, int total) 93 | { 94 | int vboxDim1; 95 | int vboxDim2; 96 | 97 | switch(color) 98 | { 99 | case 'r': 100 | vboxDim1 = vbox.R1; 101 | vboxDim2 = vbox.R2; 102 | break; 103 | case 'g': 104 | vboxDim1 = vbox.G1; 105 | vboxDim2 = vbox.G2; 106 | break; 107 | default: 108 | vboxDim1 = vbox.B1; 109 | vboxDim2 = vbox.B2; 110 | break; 111 | } 112 | 113 | for(var i = vboxDim1; i <= vboxDim2; i++) 114 | { 115 | if(partialsum[i] > total / 2) 116 | { 117 | var vbox1 = vbox.Clone(); 118 | var vbox2 = vbox.Clone(); 119 | 120 | var left = i - vboxDim1; 121 | var right = vboxDim2 - i; 122 | 123 | var d2 = left <= right 124 | ? Math.Min(vboxDim2 - 1, Math.Abs(i + right / 2)) 125 | : Math.Max(vboxDim1, Math.Abs(Convert.ToInt32(i - 1 - left / 2.0))); 126 | 127 | // avoid 0-count boxes 128 | while(d2 < 0 || partialsum[d2] <= 0) 129 | { 130 | d2++; 131 | } 132 | var count2 = lookaheadsum[d2]; 133 | while(count2 == 0 && d2 > 0 && partialsum[d2 - 1] > 0) 134 | { 135 | count2 = lookaheadsum[--d2]; 136 | } 137 | 138 | // set dimensions 139 | switch(color) 140 | { 141 | case 'r': 142 | vbox1.R2 = d2; 143 | vbox2.R1 = d2 + 1; 144 | break; 145 | case 'g': 146 | vbox1.G2 = d2; 147 | vbox2.G1 = d2 + 1; 148 | break; 149 | default: 150 | vbox1.B2 = d2; 151 | vbox2.B1 = d2 + 1; 152 | break; 153 | } 154 | 155 | return new[] {vbox1, vbox2}; 156 | } 157 | } 158 | 159 | throw new Exception("VBox can't be cut"); 160 | } 161 | 162 | private static VBox[] MedianCutApply(IList histo, VBox vbox) 163 | { 164 | if(vbox.Count(false) == 0) 165 | { 166 | return null; 167 | } 168 | if(vbox.Count(false) == 1) 169 | { 170 | return new[] {vbox.Clone(), null}; 171 | } 172 | 173 | // only one pixel, no split 174 | 175 | var rw = vbox.R2 - vbox.R1 + 1; 176 | var gw = vbox.G2 - vbox.G1 + 1; 177 | var bw = vbox.B2 - vbox.B1 + 1; 178 | var maxw = Math.Max(Math.Max(rw, gw), bw); 179 | 180 | // Find the partial sum arrays along the selected axis. 181 | var total = 0; 182 | var partialsum = new int[VboxLength]; 183 | // -1 = not set / 0 = 0 184 | for(var l = 0; l < partialsum.Length; l++) 185 | { 186 | partialsum[l] = -1; 187 | } 188 | 189 | // -1 = not set / 0 = 0 190 | var lookaheadsum = new int[VboxLength]; 191 | for(var l = 0; l < lookaheadsum.Length; l++) 192 | { 193 | lookaheadsum[l] = -1; 194 | } 195 | 196 | int i, j, k, sum, index; 197 | 198 | if(maxw == rw) 199 | { 200 | for(i = vbox.R1; i <= vbox.R2; i++) 201 | { 202 | sum = 0; 203 | for(j = vbox.G1; j <= vbox.G2; j++) 204 | { 205 | for(k = vbox.B1; k <= vbox.B2; k++) 206 | { 207 | index = GetColorIndex(i, j, k); 208 | sum += histo[index]; 209 | } 210 | } 211 | total += sum; 212 | partialsum[i] = total; 213 | } 214 | } 215 | else if(maxw == gw) 216 | { 217 | for(i = vbox.G1; i <= vbox.G2; i++) 218 | { 219 | sum = 0; 220 | for(j = vbox.R1; j <= vbox.R2; j++) 221 | { 222 | for(k = vbox.B1; k <= vbox.B2; k++) 223 | { 224 | index = GetColorIndex(j, i, k); 225 | sum += histo[index]; 226 | } 227 | } 228 | total += sum; 229 | partialsum[i] = total; 230 | } 231 | } 232 | else /* maxw == bw */ 233 | { 234 | for(i = vbox.B1; i <= vbox.B2; i++) 235 | { 236 | sum = 0; 237 | for(j = vbox.R1; j <= vbox.R2; j++) 238 | { 239 | for(k = vbox.G1; k <= vbox.G2; k++) 240 | { 241 | index = GetColorIndex(j, k, i); 242 | sum += histo[index]; 243 | } 244 | } 245 | total += sum; 246 | partialsum[i] = total; 247 | } 248 | } 249 | 250 | for(i = 0; i < VboxLength; i++) 251 | { 252 | if(partialsum[i] != -1) 253 | { 254 | lookaheadsum[i] = total - partialsum[i]; 255 | } 256 | } 257 | 258 | // determine the cut planes 259 | return maxw == rw ? DoCut('r', vbox, partialsum, lookaheadsum, total) : maxw == gw 260 | ? DoCut('g', vbox, partialsum, lookaheadsum, total) : DoCut('b', vbox, partialsum, lookaheadsum, total); 261 | } 262 | 263 | /// 264 | /// Inner function to do the iteration. 265 | /// 266 | /// The lh. 267 | /// The comparator. 268 | /// The target. 269 | /// The histo. 270 | /// vbox1 not defined; shouldn't happen! 271 | private static void Iter(List lh, IComparer comparator, int target, IList histo) 272 | { 273 | var ncolors = 1; 274 | var niters = 0; 275 | 276 | while(niters < MaxIterations) 277 | { 278 | var vbox = lh[lh.Count - 1]; 279 | if(vbox.Count(false) == 0) 280 | { 281 | lh.Sort(comparator); 282 | niters++; 283 | continue; 284 | } 285 | 286 | lh.RemoveAt(lh.Count - 1); 287 | 288 | // do the cut 289 | var vboxes = MedianCutApply(histo, vbox); 290 | var vbox1 = vboxes[0]; 291 | var vbox2 = vboxes[1]; 292 | 293 | if(vbox1 == null) 294 | { 295 | throw new Exception( 296 | "vbox1 not defined; shouldn't happen!"); 297 | } 298 | 299 | lh.Add(vbox1); 300 | if(vbox2 != null) 301 | { 302 | lh.Add(vbox2); 303 | ncolors++; 304 | } 305 | lh.Sort(comparator); 306 | 307 | if(ncolors >= target) 308 | { 309 | return; 310 | } 311 | if(niters++ > MaxIterations) 312 | { 313 | return; 314 | } 315 | } 316 | } 317 | 318 | public static CMap Quantize(int[][] pixels, int maxcolors) 319 | { 320 | // short-circuit 321 | if(pixels.Length == 0 || maxcolors < 2 || maxcolors > 256) 322 | { 323 | return null; 324 | } 325 | 326 | var histo = GetHisto(pixels); 327 | 328 | // get the beginning vbox from the colors 329 | var vbox = VboxFromPixels(pixels, histo); 330 | var pq = new List {vbox}; 331 | 332 | // Round up to have the same behaviour as in JavaScript 333 | var target = (int)Math.Ceiling(FractByPopulation * maxcolors); 334 | 335 | // first set of colors, sorted by population 336 | Iter(pq, ComparatorCount, target, histo); 337 | 338 | // Re-sort by the product of pixel occupancy times the size in color 339 | // space. 340 | pq.Sort(ComparatorProduct); 341 | 342 | // next set - generate the median cuts using the (npix * vol) sorting. 343 | Iter(pq, ComparatorProduct, maxcolors - pq.Count, histo); 344 | 345 | // Reverse to put the highest elements first into the color map 346 | pq.Reverse(); 347 | 348 | // calculate the actual colors 349 | var cmap = new CMap(); 350 | foreach(var vb in pq) 351 | { 352 | cmap.Push(vb); 353 | } 354 | 355 | return cmap; 356 | } 357 | 358 | public static double CreateComparisonValue(double saturation, double targetSaturation, double luma, double targetLuma, int population, int highestPopulation) 359 | { 360 | return WeightedMean(InvertDiff(saturation, targetSaturation), WeightSaturation, 361 | InvertDiff(luma, targetLuma), WeightLuma, 362 | population / (double)highestPopulation, WeightPopulation); 363 | } 364 | 365 | private static double WeightedMean(params double[] values) 366 | { 367 | double sum = 0; 368 | double sumWeight = 0; 369 | 370 | for(var i = 0; i < values.Length; i += 2) 371 | { 372 | var value = values[i]; 373 | var weight = values[i + 1]; 374 | 375 | sum += value * weight; 376 | sumWeight += weight; 377 | } 378 | 379 | return sum / sumWeight; 380 | } 381 | 382 | private static double InvertDiff(double value, double targetValue) 383 | { 384 | return 1 - Math.Abs(value - targetValue); 385 | } 386 | } 387 | } -------------------------------------------------------------------------------- /Runtime/Core/Mmcq.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c42e808de3d998f4d9c0c154f5470b4b 3 | timeCreated: 1512098118 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/QuantizedColor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ColorThief 4 | { 5 | public class QuantizedColor 6 | { 7 | public QuantizedColor(Color color, int population) 8 | { 9 | Color = color; 10 | Population = population; 11 | IsDark = CalculateYiqLuma(color) < 128; 12 | } 13 | 14 | public Color Color { get; private set; } 15 | public int Population { get; private set; } 16 | public bool IsDark { get; private set; } 17 | 18 | public UnityEngine.Color UnityColor 19 | { 20 | get 21 | { 22 | UnityEngine.Color color = UnityColor32; 23 | return color; 24 | } 25 | } 26 | 27 | public UnityEngine.Color UnityColor32 28 | { 29 | get 30 | { 31 | return new UnityEngine.Color32(Color.R, Color.G, Color.B, Color.A); 32 | } 33 | } 34 | 35 | public int CalculateYiqLuma(Color color) 36 | { 37 | return Convert.ToInt32(Math.Round((299 * color.R + 587 * color.G + 114 * color.B) / 1000f)); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Runtime/Core/QuantizedColor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 749ff6dcf6faf3940acefd2c4536290d 3 | timeCreated: 1512098117 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/SharedAssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // General Information about an assembly is controlled through the following 4 | // set of attributes. Change these attribute values to modify the information 5 | // associated with an assembly. 6 | 7 | [assembly: AssemblyTitle("ColorThief")] 8 | [assembly: AssemblyDescription("A code for grabbing the color palette from an image. Uses C# and .NET to make it happen.")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyProduct("ColorThief.NET")] 11 | [assembly: AssemblyCopyright("Copyright © K.Semenenko 2016")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | // Version information for an assembly consists of the following four values: 15 | // 16 | // Major Version 17 | // Minor Version 18 | // Build Number 19 | // Revision 20 | // 21 | // You can specify all the values or you can default the Build and Revision Numbers 22 | // by using the '*' as shown below: 23 | // [assembly: AssemblyVersion("1.0.*")] 24 | 25 | [assembly: AssemblyVersion("1.0.0.0")] 26 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /Runtime/Core/SharedAssemblyInfo.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f26a309917b1c2841b72bda5503ef791 3 | timeCreated: 1512098118 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Core/VBox.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace ColorThief 5 | { 6 | /// 7 | /// 3D color space box. 8 | /// 9 | internal class VBox 10 | { 11 | private readonly int[] histo; 12 | private int[] avg; 13 | public int B1; 14 | public int B2; 15 | private int? count; 16 | public int G1; 17 | public int G2; 18 | public int R1; 19 | public int R2; 20 | private int? volume; 21 | 22 | public VBox(int r1, int r2, int g1, int g2, int b1, int b2, int[] histo) 23 | { 24 | R1 = r1; 25 | R2 = r2; 26 | G1 = g1; 27 | G2 = g2; 28 | B1 = b1; 29 | B2 = b2; 30 | 31 | this.histo = histo; 32 | } 33 | 34 | public int Volume(bool force) 35 | { 36 | if(volume == null || force) 37 | { 38 | volume = (R2 - R1 + 1) * (G2 - G1 + 1) * (B2 - B1 + 1); 39 | } 40 | 41 | return volume.Value; 42 | } 43 | 44 | public int Count(bool force) 45 | { 46 | if(count == null || force) 47 | { 48 | var npix = 0; 49 | int i; 50 | 51 | for(i = R1; i <= R2; i++) 52 | { 53 | int j; 54 | for(j = G1; j <= G2; j++) 55 | { 56 | int k; 57 | for(k = B1; k <= B2; k++) 58 | { 59 | var index = Mmcq.GetColorIndex(i, j, k); 60 | npix += histo[index]; 61 | } 62 | } 63 | } 64 | 65 | count = npix; 66 | } 67 | 68 | return count.Value; 69 | } 70 | 71 | public VBox Clone() 72 | { 73 | return new VBox(R1, R2, G1, G2, B1, B2, histo); 74 | } 75 | 76 | public int[] Avg(bool force) 77 | { 78 | if(avg == null || force) 79 | { 80 | var ntot = 0; 81 | 82 | var rsum = 0; 83 | var gsum = 0; 84 | var bsum = 0; 85 | 86 | int i; 87 | 88 | for(i = R1; i <= R2; i++) 89 | { 90 | int j; 91 | for(j = G1; j <= G2; j++) 92 | { 93 | int k; 94 | for(k = B1; k <= B2; k++) 95 | { 96 | var histoindex = Mmcq.GetColorIndex(i, j, k); 97 | var hval = histo[histoindex]; 98 | ntot += hval; 99 | rsum += Convert.ToInt32((hval * (i + 0.5) * Mmcq.Mult)); 100 | gsum += Convert.ToInt32((hval * (j + 0.5) * Mmcq.Mult)); 101 | bsum += Convert.ToInt32((hval * (k + 0.5) * Mmcq.Mult)); 102 | } 103 | } 104 | } 105 | 106 | if(ntot > 0) 107 | { 108 | avg = new[] 109 | { 110 | Math.Abs(rsum / ntot), Math.Abs(gsum / ntot), 111 | Math.Abs(bsum / ntot) 112 | }; 113 | } 114 | else 115 | { 116 | avg = new[] 117 | { 118 | Math.Abs(Mmcq.Mult * (R1 + R2 + 1) / 2), 119 | Math.Abs(Mmcq.Mult * (G1 + G2 + 1) / 2), 120 | Math.Abs(Mmcq.Mult * (B1 + B2 + 1) / 2) 121 | }; 122 | } 123 | } 124 | 125 | return avg; 126 | } 127 | 128 | public bool Contains(int[] pixel) 129 | { 130 | var rval = pixel[0] >> Mmcq.Rshift; 131 | var gval = pixel[1] >> Mmcq.Rshift; 132 | var bval = pixel[2] >> Mmcq.Rshift; 133 | 134 | return rval >= R1 && rval <= R2 && gval >= G1 && gval <= G2 && bval >= B1 && bval <= B2; 135 | } 136 | } 137 | 138 | internal class VBoxCountComparer : IComparer 139 | { 140 | public int Compare(VBox x, VBox y) 141 | { 142 | var a = x.Count(false); 143 | var b = y.Count(false); 144 | return a < b ? -1 : (a > b ? 1 : 0); 145 | } 146 | } 147 | 148 | internal class VBoxComparer : IComparer 149 | { 150 | public int Compare(VBox x, VBox y) 151 | { 152 | var aCount = x.Count(false); 153 | var bCount = y.Count(false); 154 | var aVolume = x.Volume(false); 155 | var bVolume = y.Volume(false); 156 | 157 | // Otherwise sort by products 158 | var a = aCount * aVolume; 159 | var b = bCount * bVolume; 160 | return a < b ? -1 : (a > b ? 1 : 0); 161 | } 162 | } 163 | } -------------------------------------------------------------------------------- /Runtime/Core/VBox.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: be987e3fa4ca28e46876956ef484c7ba 3 | timeCreated: 1512098117 4 | licenseType: Free 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Runtime/Lokesh.ColorThief.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Lokesh.ColorThief", 3 | "rootNamespace": "", 4 | "references": [], 5 | "includePlatforms": [], 6 | "excludePlatforms": [], 7 | "allowUnsafeCode": false, 8 | "overrideReferences": true, 9 | "precompiledReferences": [], 10 | "autoReferenced": false, 11 | "defineConstraints": [], 12 | "versionDefines": [], 13 | "noEngineReferences": false 14 | } -------------------------------------------------------------------------------- /Runtime/Lokesh.ColorThief.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0e561adbb70ea454ba869c47ff2d106d 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Samples~/Demo.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEngine.UI; 5 | 6 | namespace ColorThief 7 | { 8 | public class ColorThiefDemo : MonoBehaviour 9 | { 10 | public Texture2D texture; 11 | public RawImage image; 12 | public Image dominantColor; 13 | public Image[] paletteColors; 14 | 15 | public InputField urlField; 16 | 17 | public void Download() 18 | { 19 | StartCoroutine(DownloadImage()); 20 | } 21 | 22 | IEnumerator DownloadImage() 23 | { 24 | WWW www = new WWW(urlField.text); 25 | yield return www; 26 | if(string.IsNullOrEmpty(www.error)) 27 | { 28 | texture = www.texture; 29 | image.texture = texture; 30 | float ratio = 700f/texture.height; 31 | float w = texture.width * ratio; 32 | float h = texture.height * ratio; 33 | image.rectTransform.sizeDelta = new Vector2(w, h); 34 | var dominant = new ColorThief(); 35 | dominantColor.color = dominant.GetColor(texture).UnityColor; 36 | 37 | var palette = new ColorThief(); 38 | List colors = palette.GetPalette(texture, paletteColors.Length); 39 | for(int i=0; i