2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * Copyright (C) 2017 The Android Open Source Project
21 * Modified by Woochan Lee(wc0917.lee@samsung.com)
28 internal sealed class ColorHistogram
30 private int numberColors;
32 private int[] colorCounts;
35 /// A new ColorHistogram instance.
37 public ColorHistogram(int[] pixels)
39 // Sort the pixels to enable counting below
42 // Count number of distinct colors
43 numberColors = CountDistinctColors(pixels);
44 Tizen.Log.Info("Palette", "DistinctColor Num = " + numberColors + "\n");
47 colors = new int[numberColors];
48 colorCounts = new int[numberColors];
50 // Finally count the frequency of each color
51 CountFrequencies(pixels);
55 /// return number of distinct colors in the image.
57 public int GetNumberOfColors()
63 /// return an array containing all of the distinct colors in the image.
65 public int[] GetColors()
71 /// return an array containing the frequency of a distinct colors within the image.
73 public int[] GetColorCounts()
78 private static int CountDistinctColors(int[] pixels)
80 if (pixels.Length < 2)
82 // If we have less than 2 pixels we can stop here
85 // If we have at least 2 pixels, we have a minimum of 1 color...
87 int currentColor = pixels[0];
89 // Now iterate from the second pixel to the end, counting distinct colors
90 for (int i = 1; i < pixels.Length; i++)
92 // If we encounter a new color, increase the population
93 if (pixels[i] != currentColor)
95 currentColor = pixels[i];
103 private void CountFrequencies(int[] pixels)
105 if (pixels.Length == 0)
110 int currentColorIndex = 0;
111 int currentColor = pixels[0];
113 colors[currentColorIndex] = currentColor;
114 colorCounts[currentColorIndex] = 1;
116 if (pixels.Length == 1)
118 // If we only have one pixel, we can stop here
122 // Now iterate from the second pixel to the end, population distinct colors
123 for (int i = 1; i < pixels.Length; i++)
125 if (pixels[i] == currentColor)
127 // We've hit the same color as before, increase population
128 colorCounts[currentColorIndex]++;
132 // We've hit a new color, increase index
133 currentColor = pixels[i];
135 colors[currentColorIndex] = currentColor;
136 colorCounts[currentColorIndex] = 1;