Newer
Older
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
use std::cmp::{min, Ordering};
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet};
use std::fmt::{Formatter, LowerHex, UpperHex};
use std::io::Write;
use std::path::Path;
use deltae::{Delta, LabValue, DE2000};
use image::{GenericImage, Pixel, Rgba};
use num_traits::ToPrimitive;
use crate::format::PaletteFormat;
use crate::utils::{new_image, BasicRgba};
pub type Palette = Vec<BasicRgba>;
pub fn palette(image: &impl GenericImage) -> anyhow::Result<Palette> {
let mut colours = HashSet::new();
for (_, _, pixel) in image.pixels().into_iter() {
let pixel = pixel.to_rgba();
colours.insert(Rgba::from([
pixel.0[0].to_u8().unwrap(),
pixel.0[1].to_u8().unwrap(),
pixel.0[2].to_u8().unwrap(),
pixel.0[3].to_u8().unwrap(),
// &pixel.0.map(|i| i.to_u8().unwrap())
]));
}
Ok(colours.iter().map(|c| BasicRgba::from(c)).collect())
}
struct HexStringValue(String);
trait HexString {
fn as_hex_string(&self) -> HexStringValue;
}
impl HexString for Rgba<u8> {
fn as_hex_string(&self) -> HexStringValue {
HexStringValue(format!(
"{:02X}{:02X}{:02X}{:02X}",
self.0[0], self.0[1], self.0[2], self.0[3]
))
}
}
impl<T: HexString + Clone> HexString for &T {
fn as_hex_string(&self) -> HexStringValue {
self.clone().as_hex_string()
}
}
impl UpperHex for HexStringValue {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.to_uppercase())
}
}
impl LowerHex for HexStringValue {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.to_lowercase())
}
}
pub fn write_palette<T: AsRef<Path>>(
colours: Palette,
format: PaletteFormat,
outpath: T,
) -> anyhow::Result<()> {
let mut sorted = colours.clone();
sorted.sort_by(|pa, pb| {
// format!("{:X}", pa.as_hex_string())
// .cmp(&format!("{:X}", pb.as_hex_string()))
let hue_a = pa.hue();
let hue_b = pb.hue();
println!("A: {} vs B: {}", hue_a, hue_b);
if hue_a > hue_b {
Ordering::Greater
} else if hue_b > hue_a {
Ordering::Less
} else {
Ordering::Equal
}
});
match format {
PaletteFormat::PNG => {
let num_colours = sorted.len();
let image_width = min(16, num_colours);
let image_height = if num_colours % 16 > 0 {
num_colours / image_width + 1
} else {
num_colours / image_width
};
let mut out_image = new_image(image_width as u32, image_height as u32);
for (idx, colour) in sorted.iter().enumerate() {
out_image.put_pixel(
(idx % image_width) as u32,
(idx / image_width) as u32,
Rgba::from(colour),
);
}
out_image.save(outpath)?;
}
PaletteFormat::TXT => {
let mut file = std::fs::File::create(outpath)?;
for colour in sorted.iter() {
let line = format!("#{:X}\n", colour);
file.write_all(line.as_bytes())?;
}
}
}
Ok(())
}
pub type ColourMapping = HashMap<BasicRgba, BasicRgba>;
pub fn calculate_mapping(from: &Palette, to: &Palette) -> ColourMapping {
let colour_labs = Vec::from_iter(to.iter().map(LabValue::from));
let to_palette_vectors: HashMap<usize, &BasicRgba, RandomState> =
HashMap::from_iter(to.iter().enumerate());
let mut out_map: ColourMapping = HashMap::with_capacity(from.len());
for colour in from {
let closest = to_palette_vectors
.keys()
.fold(None, |lowest, idx| match lowest {
Some(num) => {
let current = colour_labs[*idx];
let previous: LabValue = colour_labs[num];
if colour.delta(current, DE2000) < colour.delta(previous, DE2000) {
Some(*idx)
} else {
Some(num)
}
}
None => Some(*idx),
});
match closest {
Some(idx) => match to_palette_vectors.get(&idx) {
Some(col) => {
out_map.insert(colour.clone(), *col.clone());
}
None => {
println!("No matching vec for {} with col {:?}", idx, &colour);
out_map.insert(
colour.clone(),
BasicRgba {
r: 0,
g: 0,
b: 0,
a: 0,
},
);
}
},
None => {
println!("No closest for {:?}", &colour);
out_map.insert(
colour.clone(),
BasicRgba {
r: 0,
g: 0,
b: 0,
a: 0,
},
);
}
}
}
// println!("{:?}", &out_map);
out_map
}