• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.ux.material.libmonet.quantize;
18 
19 import java.util.Map;
20 import java.util.Set;
21 
22 /**
23  * An image quantizer that improves on the quality of a standard K-Means algorithm by setting the
24  * K-Means initial state to the output of a Wu quantizer, instead of random centroids. Improves on
25  * speed by several optimizations, as implemented in Wsmeans, or Weighted Square Means, K-Means with
26  * those optimizations.
27  *
28  * <p>This algorithm was designed by M. Emre Celebi, and was found in their 2011 paper, Improving
29  * the Performance of K-Means for Color Quantization. https://arxiv.org/abs/1101.0395
30  */
31 public final class QuantizerCelebi {
QuantizerCelebi()32   private QuantizerCelebi() {}
33 
34   /**
35    * Reduce the number of colors needed to represented the input, minimizing the difference between
36    * the original image and the recolored image.
37    *
38    * @param pixels Colors in ARGB format.
39    * @param maxColors The number of colors to divide the image into. A lower number of colors may be
40    *     returned.
41    * @return Map with keys of colors in ARGB format, and values of number of pixels in the original
42    *     image that correspond to the color in the quantized image.
43    */
quantize(int[] pixels, int maxColors)44   public static Map<Integer, Integer> quantize(int[] pixels, int maxColors) {
45     QuantizerWu wu = new QuantizerWu();
46     QuantizerResult wuResult = wu.quantize(pixels, maxColors);
47 
48     Set<Integer> wuClustersAsObjects = wuResult.colorToCount.keySet();
49     int index = 0;
50     int[] wuClusters = new int[wuClustersAsObjects.size()];
51     for (Integer argb : wuClustersAsObjects) {
52       wuClusters[index++] = argb;
53     }
54 
55     return QuantizerWsmeans.quantize(pixels, wuClusters, maxColors);
56   }
57 }
58