Skip to main content

libimgquant/
histogram.rs

1//! One palette for many images: frames of an animation, sprites of an atlas, tiles of a set.
2
3use std::fmt;
4
5use crate::RGBA;
6use crate::attr::{Attributes, Profile};
7use crate::error::Error;
8use crate::hist::{WEIGHT_UNITS, color_key, count_image_colors, make_histogram, remove_fixed_colors_from_histogram};
9use crate::image::Image;
10use crate::pal::{ColorLut, FPixel, cmax};
11use crate::quant::{QuantizationResult, pngquant_quantize};
12
13/// The gamma that 0 stands for: sRGB.
14const SRGB_GAMMA: f64 = 0.45455;
15
16/// A color and how many pixels have it, for [`Histogram::add_colors`].
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18pub struct HistogramEntry {
19    /// The color. Fully transparent colors are all counted as one, whatever their RGB.
20    pub color: RGBA,
21    /// Number of pixels with this color.
22    pub count: u32,
23}
24
25/// Colors collected from several images, to compute one palette for all of them.
26///
27/// Add images with [`add_image`](Self::add_image) (or colors with
28/// [`add_colors`](Self::add_colors)), then call [`quantize`](Self::quantize). The returned
29/// [`QuantizationResult`] remaps each image to the same palette, so an animated GIF can use
30/// one global color table, or a sprite sheet one PLTE chunk:
31///
32/// ```
33/// use libimgquant::{Histogram, RGBA};
34///
35/// let (width, height) = (32, 32);
36/// // Three frames of a moving gradient; only the last has blue in it.
37/// let frame = |t: usize| -> Vec<RGBA> {
38///     (0..width * height)
39///         .map(|i| {
40///             let (x, y) = (i % width, i / width);
41///             let blue = if t == 2 && x < 8 { 255 } else { 0 };
42///             RGBA::new((x * 8 + t * 20) as u8, (y * 8) as u8, blue, 255)
43///         })
44///         .collect()
45/// };
46/// let attr = libimgquant::new();
47/// let mut frames = (0..3)
48///     .map(|t| attr.new_image(frame(t), width, height, 0.0))
49///     .collect::<Result<Vec<_>, _>>()?;
50///
51/// let mut histogram = Histogram::new(&attr);
52/// for image in &mut frames {
53///     histogram.add_image(&attr, image)?;
54/// }
55/// let mut result = histogram.quantize(&attr)?;
56/// result.set_dithering_level(1.0)?;
57///
58/// let palette = result.palette_vec();
59/// for image in &mut frames {
60///     let (frame_palette, indices) = result.remapped(image)?;
61///     assert_eq!(frame_palette, palette); // one palette for every frame
62///     assert_eq!(indices.len(), width * height);
63/// }
64/// // the blue of the last frame has palette entries, although 2 of 3 frames have none
65/// assert!(palette.iter().any(|c| c.b > 200));
66/// # Ok::<(), libimgquant::Error>(())
67/// ```
68///
69/// # How images are weighted
70///
71/// Each image is counted the way [`Attributes::quantize`] counts it: at speeds that use
72/// contrast maps (1-7), pixels in noisy areas count less, and the weight of each color is
73/// limited to a tenth of the image's area, so a background color can't take over the
74/// palette. The limit applies per image, so a color shared by many frames still gets more
75/// weight than a color of one frame.
76///
77/// # Compared with [`Attributes::quantize`]
78///
79/// A histogram of one image gives a palette of the same quality as
80/// [`Attributes::quantize`], but not the same palette:
81///
82/// - colors are kept in sorted order rather than in libimagequant 2.4.1's hash table order,
83///   which changes which of two equal choices median cut makes;
84/// - weights are summed exactly, also with [`Profile::Compat`] (which otherwise reproduces
85///   2.4.1's `f32` sums), and the histogram entry limit of the speed setting is a plain limit
86///   on the number of colors;
87/// - remapping keeps the palette as it is: [`Attributes::quantize`] lets remapping move the
88///   palette towards the image's colors and, with [`Profile::Improved`], reorder it for PNG
89///   compression; neither would give every image the same palette.
90///
91/// Colors are stored exactly until [`quantize`](Self::quantize), which posterizes them only
92/// if there are more than the speed setting allows. The result is the same for any number of
93/// threads.
94#[derive(Clone)]
95pub struct Histogram {
96    /// Colors as [`color_key`]s with their weights in units of 1/[`WEIGHT_UNITS`] pixel,
97    /// sorted by key.
98    colors: Vec<(u32, u64)>,
99    fixed: Vec<RGBA>,
100    /// The gamma of everything added so far (0 already replaced by sRGB's).
101    gamma: Option<f64>,
102    profile: Profile,
103}
104
105impl fmt::Debug for Histogram {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("Histogram")
108            .field("colors", &self.colors.len())
109            .field("fixed_colors", &self.fixed)
110            .field("gamma", &self.gamma)
111            .field("profile", &self.profile)
112            .finish()
113    }
114}
115
116/// `gamma` with 0 replaced by sRGB's, or an error outside 0-1 (as for images).
117fn normalize_gamma(gamma: f64) -> Result<f64, Error> {
118    match gamma {
119        0.0 => Ok(SRGB_GAMMA),
120        g if g > 0.0 && g <= 1.0 => Ok(g),
121        _ => Err(Error::ValueOutOfRange),
122    }
123}
124
125/// Merges two lists sorted by color, adding the weights of equal colors.
126fn merge(a: &[(u32, u64)], b: &[(u32, u64)]) -> Vec<(u32, u64)> {
127    let mut out = Vec::with_capacity(a.len() + b.len());
128    let (mut i, mut j) = (0, 0);
129    while i < a.len() && j < b.len() {
130        let (x, y) = (a[i], b[j]);
131        match x.0.cmp(&y.0) {
132            std::cmp::Ordering::Less => {
133                out.push(x);
134                i += 1;
135            }
136            std::cmp::Ordering::Greater => {
137                out.push(y);
138                j += 1;
139            }
140            std::cmp::Ordering::Equal => {
141                out.push((x.0, x.1.saturating_add(y.1)));
142                i += 1;
143                j += 1;
144            }
145        }
146    }
147    out.extend_from_slice(&a[i..]);
148    out.extend_from_slice(&b[j..]);
149    out
150}
151
152/// Sorts by color and adds up the weights of equal colors. Integer sums are exact, so the
153/// order of equal colors after the (unstable) sort doesn't matter.
154fn sort_and_sum(mut colors: Vec<(u32, u64)>) -> Vec<(u32, u64)> {
155    colors.sort_unstable_by_key(|&(color, _)| color);
156    colors.dedup_by(|next, kept| {
157        if next.0 == kept.0 {
158            kept.1 = kept.1.saturating_add(next.1);
159            true
160        } else {
161            false
162        }
163    });
164    colors
165}
166
167impl Histogram {
168    /// Creates an empty histogram for images quantized with `attr`'s [`Profile`].
169    #[must_use]
170    pub fn new(attr: &Attributes) -> Self {
171        Self {
172            colors: Vec::new(),
173            fixed: Vec::new(),
174            gamma: None,
175            profile: attr.profile,
176        }
177    }
178
179    fn check(&self, attr: &Attributes, gamma: f64) -> Result<(), Error> {
180        if attr.profile != self.profile {
181            attr.log_error("the histogram was created with another profile");
182            return Err(Error::ValueOutOfRange);
183        }
184        if self.gamma.is_some_and(|g| g != gamma) {
185            attr.log_error("all images of a histogram must have the same gamma");
186            return Err(Error::ValueOutOfRange);
187        }
188        Ok(())
189    }
190
191    /// Adds the colors of `image`, weighted as [`Attributes::quantize`] weights them (see
192    /// [How images are weighted](Self#how-images-are-weighted)), and its fixed colors (see
193    /// [`Image::add_fixed_color`]).
194    ///
195    /// `attr` sets the speed, which decides whether contrast maps are used. The image keeps
196    /// the edge map it computes here for dithering when it is remapped later.
197    ///
198    /// # Errors
199    ///
200    /// - [`Error::ValueOutOfRange`] if the image's gamma differs from the gamma of the colors
201    ///   added before (gamma 0 and 0.45455 are the same), or `attr` has another [`Profile`]
202    ///   than the histogram was created with.
203    /// - [`Error::BufferTooSmall`] if there would be more than 256 fixed colors.
204    pub fn add_image(&mut self, attr: &Attributes, image: &mut Image<'_>) -> Result<(), Error> {
205        self.check(attr, image.gamma)?;
206        let new_fixed: Vec<RGBA> = image
207            .fixed_rgba
208            .iter()
209            .copied()
210            .filter(|c| !self.fixed.contains(c))
211            .collect();
212        if self.fixed.len() + new_fixed.len() > 256 {
213            return Err(Error::BufferTooSmall);
214        }
215        image.ensure_color_space(self.profile.color_space());
216        let counts = count_image_colors(image, attr);
217        attr.verbose_print(&format!("  added image to histogram...{} colors", counts.len()));
218        self.colors = merge(&self.colors, &counts);
219        for c in new_fixed {
220            if !self.fixed.contains(&c) {
221                self.fixed.push(c);
222            }
223        }
224        self.gamma = Some(image.gamma);
225        Ok(())
226    }
227
228    /// Adds colors with their pixel counts, for colors that come from elsewhere than an
229    /// [`Image`] (another histogram, a video decoder). Counts are used as they are, without
230    /// contrast weighting or the tenth-of-the-area limit.
231    ///
232    /// `gamma` is the gamma of the colors, as for [`Attributes::new_image`]; 0 means sRGB.
233    ///
234    /// ```
235    /// use libimgquant::{Histogram, HistogramEntry, RGBA};
236    ///
237    /// let attr = libimgquant::new();
238    /// let mut histogram = Histogram::new(&attr);
239    /// let entries: Vec<HistogramEntry> = (0..=255u8)
240    ///     .map(|v| HistogramEntry { color: RGBA::new(v, 255 - v, 128, 255), count: 10 })
241    ///     .collect();
242    /// histogram.add_colors(&entries, 0.0)?;
243    ///
244    /// let mut few = attr.clone();
245    /// few.set_max_colors(16)?;
246    /// let mut result = histogram.quantize(&few)?;
247    /// assert_eq!(result.palette().len(), 16);
248    /// # Ok::<(), libimgquant::Error>(())
249    /// ```
250    ///
251    /// # Errors
252    ///
253    /// [`Error::ValueOutOfRange`] if `gamma` is outside 0-1 or differs from the gamma of the
254    /// colors added before.
255    pub fn add_colors(&mut self, entries: &[HistogramEntry], gamma: f64) -> Result<(), Error> {
256        let gamma = normalize_gamma(gamma)?;
257        if self.gamma.is_some_and(|g| g != gamma) {
258            return Err(Error::ValueOutOfRange);
259        }
260        let counts: Vec<(u32, u64)> = entries
261            .iter()
262            .filter(|e| e.count > 0)
263            .map(|e| (color_key(e.color, 0), u64::from(e.count) * WEIGHT_UNITS))
264            .collect();
265        self.colors = merge(&self.colors, &sort_and_sum(counts));
266        self.gamma = Some(gamma);
267        Ok(())
268    }
269
270    /// Reserves a color that will be in the palette, like [`Image::add_fixed_color`]. Fixed
271    /// colors count towards [`Attributes::set_max_colors`]; adding a color twice has no
272    /// effect.
273    ///
274    /// ```
275    /// use libimgquant::{Histogram, RGBA};
276    ///
277    /// let pixels: Vec<RGBA> = (0..64u8).map(|i| RGBA::new(i * 4, 100, 50, 255)).collect();
278    /// let attr = libimgquant::new();
279    /// let mut image = attr.new_image(pixels, 8, 8, 0.0)?;
280    /// let mut histogram = Histogram::new(&attr);
281    /// histogram.add_image(&attr, &mut image)?;
282    /// // the transparent color of a GIF, for example
283    /// histogram.add_fixed_color(RGBA::new(0, 0, 0, 0), 0.0)?;
284    /// let palette = histogram.quantize(&attr)?.palette_vec();
285    /// assert!(palette.iter().any(|c| c.a == 0));
286    /// # Ok::<(), libimgquant::Error>(())
287    /// ```
288    ///
289    /// # Errors
290    ///
291    /// - [`Error::ValueOutOfRange`] if `gamma` is outside 0-1 or differs from the gamma of
292    ///   the colors added before.
293    /// - [`Error::BufferTooSmall`] if there are already 256 fixed colors.
294    pub fn add_fixed_color(&mut self, color: RGBA, gamma: f64) -> Result<(), Error> {
295        let gamma = normalize_gamma(gamma)?;
296        if self.gamma.is_some_and(|g| g != gamma) {
297            return Err(Error::ValueOutOfRange);
298        }
299        if !self.fixed.contains(&color) {
300            if self.fixed.len() >= 256 {
301                return Err(Error::BufferTooSmall);
302            }
303            self.fixed.push(color);
304        }
305        self.gamma = Some(gamma);
306        Ok(())
307    }
308
309    /// Computes one palette for everything added. Remap each image with the returned
310    /// [`QuantizationResult`]; every remapping uses the same palette, which
311    /// [`palette`](QuantizationResult::palette) returns before and after remapping.
312    ///
313    /// The histogram is kept, so more colors can be added and it can be quantized again.
314    ///
315    /// # Errors
316    ///
317    /// - [`Error::QualityTooLow`] if the palette can't reach the minimum quality set with
318    ///   [`Attributes::set_quality`].
319    /// - [`Error::ValueOutOfRange`] if nothing was added, or `attr` has another [`Profile`]
320    ///   than the histogram was created with.
321    pub fn quantize(&mut self, attr: &Attributes) -> Result<QuantizationResult, Error> {
322        let gamma = self.gamma.unwrap_or(SRGB_GAMMA);
323        self.check(attr, gamma)?;
324        let lut = ColorLut::new(gamma, self.profile.color_space());
325
326        // As for single images: posterize only when there are too many colors.
327        let mut ignorebits = u32::from(cmax(attr.min_posterization_output, attr.min_posterization_input));
328        let colors = loop {
329            let colors = if ignorebits == 0 {
330                self.colors.clone()
331            } else {
332                let posterized = self.colors.iter().map(|&(key, w)| {
333                    let [r, g, b, a] = key.to_le_bytes();
334                    (color_key(RGBA::new(r, g, b, a), ignorebits), w)
335                });
336                sort_and_sum(posterized.collect())
337            };
338            if colors.len() <= attr.max_histogram_entries as usize {
339                break colors;
340            }
341            if ignorebits >= 7 {
342                return Err(Error::OutOfMemory);
343            }
344            ignorebits += 1;
345            attr.verbose_print(&format!(
346                "  too many colors! Scaling colors to improve clustering... {ignorebits}"
347            ));
348        };
349
350        let len = colors.len();
351        let weights = colors
352            .into_iter()
353            .map(|(key, w)| (key, (w as f64 / WEIGHT_UNITS as f64) as f32));
354        // weights were limited per image already
355        let mut hist = make_histogram(weights, len, &lut, f32::INFINITY, ignorebits);
356        attr.verbose_print(&format!("  made histogram...{len} colors found"));
357
358        let fixed: Vec<FPixel> = self.fixed.iter().map(|&c| FPixel::from_rgba(&lut, c)).collect();
359        remove_fixed_colors_from_histogram(&mut hist, &fixed, attr.target_mse as f32);
360        let mut result = pngquant_quantize(&mut hist, attr, &fixed, gamma)?;
361        result.set_shared_palette();
362        Ok(result)
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn merge_adds_equal_colors() {
372        let a = [(1, 10), (5, 1), (9, 2)];
373        let b = [(0, 3), (5, 4), (10, 1)];
374        assert_eq!(merge(&a, &b), [(0, 3), (1, 10), (5, 5), (9, 2), (10, 1)]);
375        assert_eq!(merge(&[], &b), b);
376        assert_eq!(
377            sort_and_sum(vec![(4, 1), (2, 2), (4, 3), (2, u64::MAX)]),
378            [(2, u64::MAX), (4, 4)]
379        );
380    }
381
382    #[test]
383    fn transparent_colors_are_one_color() {
384        let attr = crate::new();
385        let mut h = Histogram::new(&attr);
386        let entries = [
387            HistogramEntry {
388                color: RGBA::new(1, 2, 3, 0),
389                count: 2,
390            },
391            HistogramEntry {
392                color: RGBA::new(9, 9, 9, 0),
393                count: 3,
394            },
395        ];
396        h.add_colors(&entries, 0.0).unwrap();
397        assert_eq!(h.colors, [(0, 5 * WEIGHT_UNITS)]);
398    }
399
400    #[test]
401    fn image_weights_are_limited_to_a_tenth_of_the_area() {
402        // one color everywhere but one pixel, no contrast maps (speed 10)
403        let mut attr = crate::new();
404        attr.set_speed(10).unwrap();
405        let mut pixels = vec![RGBA::new(10, 20, 30, 255); 100];
406        pixels[0] = RGBA::new(200, 0, 0, 255);
407        let mut image = attr.new_image(pixels, 10, 10, 0.0).unwrap();
408        let mut h = Histogram::new(&attr);
409        h.add_image(&attr, &mut image).unwrap();
410        h.add_image(&attr, &mut image).unwrap();
411        let weight = |c: RGBA| h.colors.iter().find(|e| e.0 == color_key(c, 0)).unwrap().1;
412        // 10 pixels (a tenth of 100) per image, twice
413        assert_eq!(weight(RGBA::new(10, 20, 30, 255)), 2 * 10 * WEIGHT_UNITS);
414        assert_eq!(weight(RGBA::new(200, 0, 0, 255)), 2 * WEIGHT_UNITS);
415    }
416}