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 com.google.ux.material.libmonet.utils.ColorUtils; 20 21 /** 22 * Provides conversions needed for K-Means quantization. Converting input to points, and converting 23 * the final state of the K-Means algorithm to colors. 24 */ 25 public final class PointProviderLab implements PointProvider { 26 /** 27 * Convert a color represented in ARGB to a 3-element array of L*a*b* coordinates of the color. 28 */ 29 @Override fromInt(int argb)30 public double[] fromInt(int argb) { 31 double[] lab = ColorUtils.labFromArgb(argb); 32 return new double[] {lab[0], lab[1], lab[2]}; 33 } 34 35 /** Convert a 3-element array to a color represented in ARGB. */ 36 @Override toInt(double[] lab)37 public int toInt(double[] lab) { 38 return ColorUtils.argbFromLab(lab[0], lab[1], lab[2]); 39 } 40 41 /** 42 * Standard CIE 1976 delta E formula also takes the square root, unneeded here. This method is 43 * used by quantization algorithms to compare distance, and the relative ordering is the same, 44 * with or without a square root. 45 * 46 * <p>This relatively minor optimization is helpful because this method is called at least once 47 * for each pixel in an image. 48 */ 49 @Override distance(double[] one, double[] two)50 public double distance(double[] one, double[] two) { 51 double dL = (one[0] - two[0]); 52 double dA = (one[1] - two[1]); 53 double dB = (one[2] - two[2]); 54 return (dL * dL + dA * dA + dB * dB); 55 } 56 } 57