quantette 0.6.0

Fast and high quality image quantization and palette generation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
use crate::{BoundedIndex, ImageBuf, IndexedColorMap, MAX_PIXELS, PaletteCounts};
use alloc::{borrow::ToOwned as _, vec, vec::Vec};
use core::{
    error::Error,
    fmt::{self, Debug},
};
use num_traits::AsPrimitive;
#[cfg(feature = "threads")]
use rayon::prelude::*;

/// The error returned when an [`IndexedImage`] failed to be created.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateIndexedImageError<Color, Index = u8> {
    /// The provided image width.
    width: u32,
    /// The provided image height.
    height: u32,
    /// The provided image palette.
    palette: Vec<Color>,
    /// The provided image indices.
    indices: Vec<Index>,
}

impl<Color, Index> CreateIndexedImageError<Color, Index> {
    /// Returns a reference to the palette [`Vec`] that was used to try and create the [`IndexedImage`].
    #[inline]
    pub fn palette(&self) -> &[Color] {
        &self.palette
    }

    /// Returns a reference to the indices [`Vec`] that was used to try and create the [`IndexedImage`].
    #[inline]
    pub fn indices(&self) -> &[Index] {
        &self.indices
    }

    /// Returns the palette and indices that were used to try and create the [`IndexedImage`].
    #[must_use]
    #[inline]
    pub fn into_parts(self) -> (Vec<Color>, Vec<Index>) {
        let Self { palette, indices, .. } = self;
        (palette, indices)
    }
}

impl<Color, Index> fmt::Display for CreateIndexedImageError<Color, Index> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { width, height, .. } = *self;
        if width.checked_mul(height).is_some() {
            write!(
                f,
                "image dimensions of ({width}, {height}) do not match the indices length of {}",
                self.indices.len(),
            )
        } else {
            write!(
                f,
                "image dimensions of ({width}, {height}) are above the maximum number of pixels of {MAX_PIXELS}",
            )
        }
    }
}

impl<Color: Debug, Index: Debug> Error for CreateIndexedImageError<Color, Index> {}

/// An image represented as a palette of colors and a series of indices into that palette.
///
/// This type consists of a width, a height, a palette buffer, and an indices buffer.
/// The indices buffer is in row-major order where each index corresponds to one pixel and
/// references one of the palette colors. The length of the indices [`Vec`] is guaranteed to match
/// `width * height` and be less than or equal to [`MAX_PIXELS`].
///
/// The default index type is `u8`, but may also be `u16` or `u32`. Note that `u16` or `u32` may
/// not be fully supported by other functions throughout the crate.
///
/// # Examples
///
/// Directly creating an [`IndexedImage`] from a [`Vec`] of palette colors and indices:
///
/// ```
/// # use quantette::{IndexedImage, CreateIndexedImageError};
/// # use palette::Srgb;
/// # fn main() -> Result<(), CreateIndexedImageError<Srgb<u8>>> {
/// let (width, height) = (512, 512);
/// let palette = vec![Srgb::new(0, 0, 0)];
/// let indices = vec![0; (width * height) as usize];
/// let image = IndexedImage::new(width, height, palette, indices)?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IndexedImage<Color, Index = u8> {
    /// The width of the image.
    width: u32,
    /// The height of the image.
    height: u32,
    /// The palette color of the image.
    palette: Vec<Color>,
    /// The indices into `palette` for each pixel of the image.
    indices: Vec<Index>,
}

impl<Color, Index: BoundedIndex> IndexedImage<Color, Index> {
    /// Create a new [`IndexedImage`] without validating invariants.
    pub(crate) fn new_unchecked(
        width: u32,
        height: u32,
        palette: Vec<Color>,
        indices: Vec<Index>,
    ) -> Self {
        debug_assert_eq!(
            width.checked_mul(height).map(|len| len as usize),
            Some(indices.len()),
        );
        debug_assert!(indices.iter().all(|i| i.as_() < palette.len()));
        Self { width, height, palette, indices }
    }

    /// Create a new [`IndexedImage`] from a `palette` of colors and `indices` into the `palette`.
    ///
    /// # Errors
    ///
    /// The provided `palette` and `indices` are returned as an `Err` if any of the following are true:
    /// - The length of `indices` and `width * height` do not match.
    /// - `width * height` overflows a `u32`.
    ///
    /// Note that this function does not validate that all indices in `indices`
    /// are less than `palette.len()`.
    pub fn new(
        width: u32,
        height: u32,
        palette: Vec<Color>,
        indices: Vec<Index>,
    ) -> Result<Self, CreateIndexedImageError<Color, Index>> {
        if width.checked_mul(height).map(|len| len as usize) == Some(indices.len()) {
            Ok(Self::new_unchecked(width, height, palette, indices))
        } else {
            Err(CreateIndexedImageError { width, height, palette, indices })
        }
    }

    /// Returns the width and height of the [`IndexedImage`].
    #[inline]
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Returns the width the [`IndexedImage`].
    #[inline]
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Returns the height of the [`IndexedImage`].
    #[inline]
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Returns whether the [`IndexedImage`] has zero pixels.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.indices.is_empty()
    }

    /// Returns the number of pixels in the [`IndexedImage`] specified by `width * height`.
    #[allow(clippy::cast_possible_truncation)]
    #[inline]
    pub fn num_pixels(&self) -> u32 {
        self.indices.len() as u32
    }

    /// Returns a slice of the palette colors of the [`IndexedImage`].
    #[inline]
    pub fn palette(&self) -> &[Color] {
        &self.palette
    }

    /// Returns a mutable slice of the palette colors of the [`IndexedImage`].
    #[inline]
    pub fn palette_mut(&mut self) -> &mut [Color] {
        &mut self.palette
    }

    /// Returns a slice of the indices of the [`IndexedImage`].
    #[inline]
    pub fn indices(&self) -> &[Index] {
        &self.indices
    }

    /// Returns a mutable slice of the indices of the [`IndexedImage`].
    #[inline]
    pub fn indices_mut(&mut self) -> &mut [Index] {
        &mut self.indices
    }

    /// Consume an [`IndexedImage`] and return the inner palette [`Vec`] and indices [`Vec`].
    #[must_use]
    #[inline]
    pub fn into_parts(self) -> (Vec<Color>, Vec<Index>) {
        let Self { palette, indices, .. } = self;
        (palette, indices)
    }

    /// Create a new [`IndexedImage`] with a larger index type.
    ///
    /// See also [`into_larger_indices`](Self::into_larger_indices) for a consuming variant
    /// that does not need to clone the palette.
    #[must_use]
    pub fn to_larger_indices<NewIndex>(&self) -> IndexedImage<Color, NewIndex>
    where
        Color: Clone,
        NewIndex: BoundedIndex,
        Index: Into<NewIndex>,
    {
        let Self { width, height, palette, indices, .. } = self;
        IndexedImage::new_unchecked(
            *width,
            *height,
            palette.clone(),
            indices.iter().map(|&i| i.into()).collect(),
        )
    }

    /// Create a new [`IndexedImage`] with a smaller index type.
    ///
    /// See also [`into_smaller_indices`](Self::into_smaller_indices) for a consuming variant
    /// that does not need to clone the palette.
    ///
    /// This returns `None` if the length of the palette is larger than `NewIndex::MAX + 1`.
    #[must_use]
    pub fn to_smaller_indices<NewIndex>(&self) -> Option<IndexedImage<Color, NewIndex>>
    where
        Color: Clone,
        NewIndex: BoundedIndex,
        Index: AsPrimitive<NewIndex>,
    {
        let Self { width, height, palette, indices, .. } = self;
        (palette.len() <= NewIndex::MAX_LEN).then(|| {
            let palette = palette.to_owned();
            let indices = indices.iter().map(|i| i.as_()).collect();
            IndexedImage::new_unchecked(*width, *height, palette, indices)
        })
    }

    /// Convert the indices of an [`IndexedImage`] to a larger integer type.
    ///
    /// See [`to_larger_indices`](Self::to_larger_indices) for a non-consuming variant.
    #[must_use]
    pub fn into_larger_indices<NewIndex>(self) -> IndexedImage<Color, NewIndex>
    where
        NewIndex: BoundedIndex,
        Index: Into<NewIndex>,
    {
        let Self { width, height, palette, indices, .. } = self;
        IndexedImage::new_unchecked(
            width,
            height,
            palette,
            indices.into_iter().map(Into::into).collect(),
        )
    }

    /// Convert the indices of an [`IndexedImage`] to a smaller integer type.
    ///
    /// See [`to_smaller_indices`](Self::to_smaller_indices) for a non-consuming variant.
    ///
    /// # Errors
    ///
    /// This returns the original [`IndexedImage`] as an `Err` if the length of the palette is
    /// larger than `NewIndex::MAX + 1`.
    ///
    pub fn into_smaller_indices<NewIndex>(self) -> Result<IndexedImage<Color, NewIndex>, Self>
    where
        NewIndex: BoundedIndex,
        Index: AsPrimitive<NewIndex>,
    {
        if self.palette.len() <= NewIndex::MAX_LEN {
            let Self { width, height, palette, indices, .. } = self;
            let indices = indices.into_iter().map(AsPrimitive::as_).collect();
            Ok(IndexedImage::new_unchecked(width, height, palette, indices))
        } else {
            Err(self)
        }
    }

    /// Replace the palette of an [`IndexedImage`] to a different color type (or to new colors
    /// of the same type).
    ///
    /// # Errors
    ///
    /// If the length of the provided `palette` does not match the length of the current palette
    /// in the [`IndexedImage`], then `self` and `palette` are returned as an `Err`. Otherwise,
    /// the new [`IndexedImage`] is returned alongside the old palette.
    #[allow(clippy::type_complexity)]
    #[inline]
    pub fn replace_palette<NewColor>(
        self,
        palette: Vec<NewColor>,
    ) -> Result<(IndexedImage<NewColor, Index>, Vec<Color>), (Self, Vec<NewColor>)> {
        if self.palette.len() == palette.len() {
            let Self {
                width,
                height,
                indices,
                palette: old_palette,
                ..
            } = self;
            Ok((
                IndexedImage::new_unchecked(width, height, palette, indices),
                old_palette,
            ))
        } else {
            Err((self, palette))
        }
    }

    /// Map the palette of an [`IndexedImage`], reusing the existing `indices`.
    ///
    /// See [`map_ref`](IndexedImage::map_ref) to instead clone the existing `indices`
    /// and retain the original [`IndexedImage`].
    ///
    /// Also see [`map_to_indexed`](IndexedImage::map_to_indexed) to map an [`IndexedImage`] to a
    /// new palette with a potentially different number of colors.
    ///
    /// Rather than being a function from `Color -> NewColor`, `mapping` takes the whole palette
    /// as input and returns a new palette. This is to allow batch or parallel mappings.
    ///
    /// # Examples
    ///
    /// It is recommended to do batch mappings for efficiency where it makes sense. E.g., using the
    /// color space conversion functions from the [`color_space`](crate::color_space) module.
    ///
    /// ```
    /// # use quantette::IndexedImage;
    /// # use palette::{Srgb, LinSrgb};
    /// use quantette::color_space::srgb8_to_oklab;
    /// let srgb_image = IndexedImage::<Srgb<u8>>::default();
    /// let oklab_image = srgb_image.map(|palette| srgb8_to_oklab(&palette));
    /// ```
    ///
    /// To instead map each color one at a time, use `into_iter`, `map`, and `collect` like normal:
    ///
    /// ```
    /// # use quantette::IndexedImage;
    /// # use palette::{Srgb, LinSrgb};
    /// let srgb_image = IndexedImage::<Srgb<u8>>::default();
    /// let lin_srgb_image: IndexedImage<LinSrgb> =
    ///     srgb_image.map(|palette| palette.into_iter().map(|srgb| srgb.into_linear()).collect());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `mapping` returns a palette with a different length than the original palette.
    #[must_use]
    #[inline]
    pub fn map<NewColor>(
        self,
        mapping: impl FnOnce(Vec<Color>) -> Vec<NewColor>,
    ) -> IndexedImage<NewColor, Index> {
        let Self { width, height, palette, indices, .. } = self;
        let len = palette.len();
        let palette = mapping(palette);
        assert_eq!(palette.len(), len);
        IndexedImage::new_unchecked(width, height, palette, indices)
    }

    /// Map the palette of an [`IndexedImage`], cloning the existing `indices`.
    ///
    /// See [`map`](IndexedImage::map) to instead consume the original
    /// [`IndexedImage`] and avoid a clone of the `indices`.
    ///
    /// Also see [`map_to_indexed`](IndexedImage::map_to_indexed) to map an [`IndexedImage`] to a
    /// new palette with a potentially different number of colors.
    ///
    /// Rather than being a function from `Color -> NewColor`, `mapping` takes the whole palette
    /// as input and returns a new palette. This is to allow batch or parallel mappings.
    ///
    /// # Examples
    ///
    /// It is recommended to do batch mappings for efficiency where it makes sense. E.g., using the
    /// color space conversion functions from the [`color_space`](crate::color_space) module.
    ///
    /// ```
    /// # use quantette::IndexedImage;
    /// # use palette::{Srgb, LinSrgb};
    /// use quantette::color_space::srgb8_to_oklab;
    /// let srgb_image = IndexedImage::<Srgb<u8>>::default();
    /// let oklab_image = srgb_image.map_ref(srgb8_to_oklab);
    /// ```
    ///
    /// To instead map each color one at a time, use `iter`, `map`, and `collect` like normal:
    ///
    /// ```
    /// # use quantette::IndexedImage;
    /// # use palette::{Srgb, LinSrgb};
    /// let srgb_image = IndexedImage::<Srgb<u8>>::default();
    /// let lin_srgb_image: IndexedImage<LinSrgb> =
    ///     srgb_image.map_ref(|palette| palette.iter().map(|srgb| srgb.into_linear()).collect());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `mapping` returns a palette with a different length than the original palette.
    #[must_use]
    #[inline]
    pub fn map_ref<NewColor>(
        &self,
        mapping: impl FnOnce(&[Color]) -> Vec<NewColor>,
    ) -> IndexedImage<NewColor, Index> {
        let len = self.palette().len();
        let palette = mapping(self.palette());
        assert_eq!(palette.len(), len);
        IndexedImage::new_unchecked(self.width, self.height, palette, self.indices.clone())
    }

    /// Map an [`IndexedImage`] to a new palette using the provided [`IndexedColorMap`].
    ///
    /// This function recalculates the `indices` for the new [`IndexedImage`], as the new palette
    /// may have a different length. To map only the palette colors see one of the following:
    /// - [`map_ref`](IndexedImage::map_ref)
    /// - [`map`](IndexedImage::map)
    /// - [`replace_palette`](IndexedImage::replace_palette)
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    pub fn map_to_indexed<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> IndexedImage<ColorMap::Output> {
        let indices = color_map.map_to_indices(&self.palette);
        assert_eq!(indices.len(), self.palette.len());
        let indices = {
            let indices = indices.as_slice(); // faster for some reason
            self.indices.iter().map(|i| indices[i.as_()]).collect()
        };
        IndexedImage::new_unchecked(
            self.width,
            self.height,
            color_map.into_palette().into_vec(),
            indices,
        )
    }

    #[cfg(feature = "threads")]
    /// Map an [`IndexedImage`] to a new palette in parallel using the provided [`IndexedColorMap`].
    ///
    /// This function recalculates the `indices` for the new [`IndexedImage`], as the new palette
    /// may have a different length. To map only the palette colors see one of the following:
    /// - [`map_ref`](IndexedImage::map_ref)
    /// - [`map`](IndexedImage::map)
    /// - [`replace_palette`](IndexedImage::replace_palette)
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    pub fn map_to_indexed_par<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> IndexedImage<ColorMap::Output> {
        let indices = color_map.map_to_indices(&self.palette);
        assert_eq!(indices.len(), self.palette.len());
        let indices = {
            let indices = indices.as_slice(); // faster for some reason
            self.indices.par_iter().map(|i| indices[i.as_()]).collect()
        };
        IndexedImage::new_unchecked(
            self.width,
            self.height,
            color_map.into_palette().into_vec(),
            indices,
        )
    }

    /// Convert an [`IndexedImage`] to an [`ImageBuf`] while also mapping the palette colors.
    ///
    /// This is more efficient than [`map_ref`](Self::map_ref) followed by
    /// [`to_image`](Self::to_image), since it avoids unnecessary intermediate `indices`.
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    pub fn map_to_image<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> ImageBuf<ColorMap::Output> {
        let Self { width, height, .. } = *self;
        let palette = color_map.map_to_colors(&self.palette);
        assert_eq!(palette.len(), self.palette.len());
        let palette = palette.as_slice();
        let pixels = self
            .indices
            .iter()
            .map(|i| palette[i.as_()].clone())
            .collect();
        ImageBuf::new_unchecked(width, height, pixels)
    }

    #[cfg(feature = "threads")]
    /// Convert an [`IndexedImage`] to an [`ImageBuf`] in parallel while also mapping the palette colors.
    ///
    /// This is more efficient than [`map_ref`](Self::map_ref) followed by
    /// [`to_image_par`](Self::to_image_par), since it avoids unnecessary intermediate `indices`.
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    pub fn map_to_image_par<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> ImageBuf<ColorMap::Output> {
        let Self { width, height, .. } = *self;
        let palette = color_map.map_to_colors(&self.palette);
        assert_eq!(palette.len(), self.palette.len());
        let palette = palette.as_slice();
        let pixels = self
            .indices
            .par_iter()
            .map(|i| palette[i.as_()].clone())
            .collect();
        ImageBuf::new_unchecked(width, height, pixels)
    }

    /// Convert an [`IndexedImage`] to an [`IndexedImageCounts`] by counting the number of times
    /// each palette index appears.
    #[must_use]
    pub fn into_indexed_image_counts(self) -> IndexedImageCounts<Color, Index> {
        let mut counts = vec![0; self.palette.len()];
        for i in &self.indices {
            counts[i.as_()] += 1;
        }
        IndexedImageCounts { image: self, counts }
    }

    /// Convert an [`IndexedImage`] to an [`ImageBuf`].
    ///
    /// See [`map_to_image`](Self::map_to_image) if you also need to map the palette colors.
    #[must_use]
    pub fn to_image(&self) -> ImageBuf<Color>
    where
        Color: Clone,
    {
        let Self { width, height, .. } = *self;
        let palette = self.palette.as_slice();
        let pixels = self
            .indices
            .iter()
            .map(|i| palette[i.as_()].clone())
            .collect();
        ImageBuf::new_unchecked(width, height, pixels)
    }

    #[cfg(feature = "threads")]
    /// Convert an [`IndexedImage`] to an [`ImageBuf`] in parallel.
    ///
    /// See [`map_to_image_par`](Self::map_to_image_par) if you also need to map the palette colors.
    #[must_use]
    pub fn to_image_par(&self) -> ImageBuf<Color>
    where
        Color: Clone + Send + Sync,
    {
        let Self { width, height, .. } = *self;
        let palette = self.palette.as_slice();
        let pixels = self
            .indices
            .par_iter()
            .map(|i| palette[i.as_()].clone())
            .collect();
        ImageBuf::new_unchecked(width, height, pixels)
    }
}

impl<Color, Index: BoundedIndex> Default for IndexedImage<Color, Index> {
    #[inline]
    fn default() -> Self {
        Self::new_unchecked(0, 0, Vec::new(), Vec::new())
    }
}

/// An image represented as a palette of colors and a series of indices into that palette.
/// This type also stores the number of times each palette color is referenced.
///
/// This type consists of a width, a height, a palette buffer, an indices buffer, and a counts buffer.
/// The indices buffer is in row-major order where each index corresponds to one pixel and
/// references one of the palette colors. The length of the indices [`Vec`] is guaranteed to match
/// `width * height` and be less than or equal to [`MAX_PIXELS`]. Similarly, the length of the
/// palette is guaranteed to be the same length as the counts buffer.
///
/// The default index type is `u8`, but may also be `u16` or `u32`. Note that `u16` or `u32` may
/// not be fully supported by other functions throughout the crate.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IndexedImageCounts<Color, Index = u8> {
    /// The underlying [`IndexedImage`].
    image: IndexedImage<Color, Index>,
    /// The counts corresponding to each palette color.
    counts: Vec<u32>,
}

impl<Color, Index: BoundedIndex> IndexedImageCounts<Color, Index> {
    /// Create a new [`IndexedImageCounts`] without validating invariants.
    #[inline]
    pub(crate) fn new_unchecked(
        width: u32,
        height: u32,
        palette: Vec<Color>,
        counts: Vec<u32>,
        indices: Vec<Index>,
    ) -> Self {
        let image = IndexedImage::new_unchecked(width, height, palette, indices);
        Self::from_indexed_image_unchecked(image, counts)
    }

    /// Create a new [`IndexedImageCounts`] from a [`PaletteCounts`] without validating invariants.
    #[inline]
    pub(crate) fn from_palette_counts_unchecked(
        width: u32,
        height: u32,
        palette_counts: PaletteCounts<Color>,
        indices: Vec<Index>,
    ) -> Self {
        let (palette, counts) = palette_counts.into_parts();
        Self::new_unchecked(width, height, palette, counts, indices)
    }

    /// Create a new [`IndexedImageCounts`] from an [`IndexedImage`] without validating invariants.
    #[inline]
    pub(crate) fn from_indexed_image_unchecked(
        image: IndexedImage<Color, Index>,
        counts: Vec<u32>,
    ) -> Self {
        debug_assert_eq!(image.palette.len(), counts.len());
        debug_assert_eq!(
            image.indices().len(),
            counts.iter().copied().sum::<u32>() as usize,
        );
        Self { image, counts }
    }

    /// Returns the width and height of the [`IndexedImageCounts`].
    #[inline]
    pub fn dimensions(&self) -> (u32, u32) {
        self.image.dimensions()
    }

    /// Returns the width of the [`IndexedImageCounts`].
    #[inline]
    pub fn width(&self) -> u32 {
        self.image.width()
    }

    /// Returns the height of the [`IndexedImageCounts`].
    #[inline]
    pub fn height(&self) -> u32 {
        self.image.height()
    }

    /// Returns whether the [`IndexedImageCounts`] has zero pixels.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.image.is_empty()
    }

    /// Returns the number of pixels in the [`IndexedImageCounts`] specified by `width * height`.
    #[inline]
    pub fn num_pixels(&self) -> u32 {
        self.image.num_pixels()
    }

    /// Returns a reference to an [`IndexedImage`] from a reference to an [`IndexedImageCounts`].
    #[inline]
    pub fn as_indexed_image(&self) -> &IndexedImage<Color, Index> {
        &self.image
    }

    /// Returns a slice of the palette colors of the [`IndexedImageCounts`].
    #[inline]
    pub fn palette(&self) -> &[Color] {
        self.image.palette()
    }

    /// Returns a mutable slice of the palette colors of the [`IndexedImageCounts`].
    #[inline]
    pub fn palette_mut(&mut self) -> &mut [Color] {
        self.image.palette_mut()
    }

    /// Returns a slice of the inner counts of the [`IndexedImageCounts`].
    #[inline]
    pub fn counts(&self) -> &[u32] {
        &self.counts
    }

    /// Returns a slice of the indices of the [`IndexedImageCounts`].
    #[inline]
    pub fn indices(&self) -> &[Index] {
        self.image.indices()
    }

    /// Returns the sum of the [`counts`](Self::counts) for all palette colors.
    ///
    /// This operation is `O(1)` and is the same as [`num_pixels`](Self::num_pixels).
    #[inline]
    pub fn total_count(&self) -> u32 {
        self.image.num_pixels()
    }

    /// Consume an [`IndexedImageCounts`] and convert it to an [`IndexedImage`].
    #[must_use]
    #[inline]
    pub fn into_indexed_image(self) -> IndexedImage<Color, Index> {
        self.image
    }

    /// Consume an [`IndexedImageCounts`] and convert it to a [`PaletteCounts`].
    #[must_use]
    #[inline]
    pub fn into_palette_counts(self) -> PaletteCounts<Color> {
        let total_count = self.total_count();
        let Self { image, counts, .. } = self;
        PaletteCounts::new_unchecked(image.palette, counts, total_count)
    }

    /// Consume an [`IndexedImageCounts`] and return the inner [`IndexedImage`]
    /// and [`Vec`] of counts.
    #[must_use]
    #[inline]
    pub fn into_parts(self) -> (IndexedImage<Color, Index>, Vec<u32>) {
        let Self { image, counts, .. } = self;
        (image, counts)
    }

    /// Replace the palette of an [`IndexedImageCounts`] to a different color type (or to new colors
    /// of the same type).
    ///
    /// # Errors
    ///
    /// If the length of the provided `palette` does not match the length of the current palette
    /// in the [`IndexedImageCounts`], then `self` and `palette` are returned as an `Err`.
    /// Otherwise, the new [`IndexedImageCounts`] is returned alongside the old palette.
    #[allow(clippy::type_complexity)]
    #[inline]
    pub fn replace_palette<NewColor>(
        self,
        palette: Vec<NewColor>,
    ) -> Result<(IndexedImageCounts<NewColor, Index>, Vec<Color>), (Self, Vec<NewColor>)> {
        if self.palette().len() == palette.len() {
            let IndexedImage {
                width,
                height,
                palette: old_palette,
                indices,
                ..
            } = self.image;
            Ok((
                IndexedImageCounts::new_unchecked(width, height, palette, self.counts, indices),
                old_palette,
            ))
        } else {
            Err((self, palette))
        }
    }

    /// Map the palette of an [`IndexedImageCounts`], reusing the existing `indices` and `counts`.
    ///
    /// See [`map_ref`](IndexedImageCounts::map_ref) to instead clone the existing `indices` and
    /// `counts` while retaining the original [`IndexedImageCounts`].
    ///
    /// Also see [`map_to_indexed`](IndexedImageCounts::map_to_indexed) to map an
    /// [`IndexedImageCounts`] to a new palette with a potentially different number of colors.
    ///
    /// Rather than being a function from `Color -> NewColor`, `mapping` takes the whole palette
    /// as input and returns a new palette. This is to allow batch or parallel mappings.
    ///
    /// # Examples
    ///
    /// It is recommended to do batch mappings for efficiency where it makes sense. E.g., using the
    /// color space conversion functions from the [`color_space`](crate::color_space) module.
    ///
    /// ```
    /// # use quantette::IndexedImageCounts;
    /// # use palette::{Srgb, LinSrgb};
    /// use quantette::color_space::srgb8_to_oklab;
    /// let srgb_counts = IndexedImageCounts::<Srgb<u8>>::default();
    /// let oklab_counts = srgb_counts.map(|palette| srgb8_to_oklab(&palette));
    /// ```
    ///
    /// To instead map each color one at a time, use `into_iter`, `map`, and `collect` like normal:
    ///
    /// ```
    /// # use quantette::IndexedImageCounts;
    /// # use palette::{Srgb, LinSrgb};
    /// let srgb_counts = IndexedImageCounts::<Srgb<u8>>::default();
    /// let lin_srgb_counts: IndexedImageCounts<LinSrgb> =
    ///     srgb_counts.map(|palette| palette.into_iter().map(|srgb| srgb.into_linear()).collect());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `mapping` returns a palette with a different length than the original palette.
    #[must_use]
    #[inline]
    pub fn map<NewColor>(
        self,
        mapping: impl FnOnce(Vec<Color>) -> Vec<NewColor>,
    ) -> IndexedImageCounts<NewColor, Index> {
        let Self { image, counts } = self;
        let image = image.map(mapping);
        IndexedImageCounts::from_indexed_image_unchecked(image, counts)
    }

    /// Map the palette of an [`IndexedImageCounts`], cloning the existing `indices` and `counts`.
    ///
    /// See [`map`](IndexedImageCounts::map) to instead consume the original [`IndexedImageCounts`]
    /// and avoid a clone of the `indices` and `counts`.
    ///
    /// Also see [`map_to_indexed`](IndexedImageCounts::map_to_indexed) to map an
    /// [`IndexedImageCounts`] to a new palette with a potentially different number of colors.
    ///
    /// Rather than being a function from `Color -> NewColor`, `mapping` takes the whole palette
    /// as input and returns a new palette. This is to allow batch or parallel mappings.
    ///
    /// # Examples
    ///
    /// It is recommended to do batch mappings for efficiency where it makes sense. E.g., using the
    /// color space conversion functions from the [`color_space`](crate::color_space) module.
    ///
    /// ```
    /// # use quantette::IndexedImageCounts;
    /// # use palette::{Srgb, LinSrgb};
    /// use quantette::color_space::srgb8_to_oklab;
    /// let srgb_counts = IndexedImageCounts::<Srgb<u8>>::default();
    /// let oklab_counts = srgb_counts.map_ref(srgb8_to_oklab);
    /// ```
    ///
    /// To instead map each color one at a time, use `iter`, `map`, and `collect` like normal:
    ///
    /// ```
    /// # use quantette::IndexedImageCounts;
    /// # use palette::{Srgb, LinSrgb};
    /// let srgb_counts = IndexedImageCounts::<Srgb<u8>>::default();
    /// let lin_srgb_counts: IndexedImageCounts<LinSrgb> =
    ///     srgb_counts.map_ref(|palette| palette.iter().map(|srgb| srgb.into_linear()).collect());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `mapping` returns a palette with a different length than the original palette.
    #[must_use]
    #[inline]
    pub fn map_ref<NewColor>(
        &self,
        mapping: impl FnOnce(&[Color]) -> Vec<NewColor>,
    ) -> IndexedImageCounts<NewColor, Index> {
        let Self { image, counts } = self;
        let image = image.map_ref(mapping);
        IndexedImageCounts::from_indexed_image_unchecked(image, counts.clone())
    }

    /// Map an [`IndexedImageCounts`] to a new palette using the provided [`IndexedColorMap`].
    ///
    /// This function recalculates the `indices` for the new [`IndexedImage`], as the new palette
    /// may have a different length. To map only the palette colors see one of the following:
    /// - [`map_ref`](IndexedImageCounts::map_ref)
    /// - [`map`](IndexedImageCounts::map)
    /// - [`replace_palette`](IndexedImageCounts::replace_palette)
    ///
    /// Note that this returns an [`IndexedImage`] and if you want to recalculate the `counts` to
    /// create a new [`IndexedImageCounts`], then use
    /// [`into_indexed_image_counts`](IndexedImage::into_indexed_image_counts).
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    #[inline]
    pub fn map_to_indexed<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> IndexedImage<ColorMap::Output> {
        self.image.map_to_indexed(color_map)
    }

    #[cfg(feature = "threads")]
    /// Map an [`IndexedImageCounts`] to a new palette in parallel using the provided
    /// [`IndexedColorMap`].
    ///
    /// This function recalculates the `indices` for the new [`IndexedImage`], as the new palette
    /// may have a different length. To map only the palette colors see one of the following:
    /// - [`map_ref`](IndexedImageCounts::map_ref)
    /// - [`map`](IndexedImageCounts::map)
    /// - [`replace_palette`](IndexedImageCounts::replace_palette)
    ///
    /// Note that this returns an [`IndexedImage`] and if you want to recalculate the `counts` to
    /// create a new [`IndexedImageCounts`], then use
    /// [`into_indexed_image_counts`](IndexedImage::into_indexed_image_counts).
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    #[inline]
    pub fn map_to_indexed_par<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> IndexedImage<ColorMap::Output> {
        self.image.map_to_indexed_par(color_map)
    }

    /// Convert an [`IndexedImageCounts`] to an [`ImageBuf`] while also mapping the palette colors.
    ///
    /// This is more efficient than [`map_ref`](Self::map_ref) followed by
    /// [`to_image`](Self::to_image), since it avoids unnecessary intermediate `indices`.
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    #[inline]
    pub fn map_to_image<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> ImageBuf<ColorMap::Output> {
        self.image.map_to_image(color_map)
    }

    #[cfg(feature = "threads")]
    /// Convert an [`IndexedImageCounts`] to an [`ImageBuf`] in parallel while also mapping the
    /// palette colors.
    ///
    /// This is more efficient than [`map_ref`](Self::map_ref) followed by
    /// [`to_image_par`](Self::to_image_par), since it avoids unnecessary intermediate `indices`.
    ///
    /// # Panics
    ///
    /// Panics if `color_map` is not a valid implementor of [`IndexedColorMap`]. That is, it returns
    /// a [`Vec`] with a different length than the input slice.
    #[must_use]
    #[inline]
    pub fn map_to_image_par<ColorMap: IndexedColorMap<Color>>(
        &self,
        color_map: ColorMap,
    ) -> ImageBuf<ColorMap::Output> {
        self.image.map_to_image_par(color_map)
    }

    /// Convert an [`IndexedImageCounts`] to an [`ImageBuf`].
    ///
    /// See [`map_to_image`](Self::map_to_image) if you also need to map the palette colors.
    #[must_use]
    #[inline]
    pub fn to_image(&self) -> ImageBuf<Color>
    where
        Color: Clone,
    {
        self.image.to_image()
    }

    #[cfg(feature = "threads")]
    /// Convert an [`IndexedImageCounts`] to an [`ImageBuf`] in parallel.
    ///
    /// See [`map_to_image_par`](Self::map_to_image_par) if you also need to map the palette colors.
    #[must_use]
    #[inline]
    pub fn to_image_par(&self) -> ImageBuf<Color>
    where
        Color: Clone + Send + Sync,
    {
        self.image.to_image_par()
    }
}

impl<Color, Index: BoundedIndex> Default for IndexedImageCounts<Color, Index> {
    #[inline]
    fn default() -> Self {
        Self::from_indexed_image_unchecked(IndexedImage::default(), Vec::new())
    }
}

impl<Color, Index: BoundedIndex> AsRef<IndexedImage<Color, Index>>
    for IndexedImageCounts<Color, Index>
{
    #[inline]
    fn as_ref(&self) -> &IndexedImage<Color, Index> {
        self.as_indexed_image()
    }
}