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 | //! Takes sRGB PPM files as input
//! I know PPM isn't sRGB according to the spec
//! But even in the spec they mention putting sRGB data in
//! So fuck the spec it assumes sRGB
//! Usage: input output [target temperature] [source temperature]
//! Default target is 4000K, default source is 6500K
//! Temperatures are in Kelvin
//! Not much output apart from that. It's a tad slow but does its job.
use std::env::Args;
use std::error::Error;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::ErrorKind;
use std::io::prelude::*;
use std::path::Path;
use std::str::FromStr;
/// Second radiation constant
/// Source: https://en.wikipedia.org/wiki/Planckian_locus#International_Temperature_Scale
const C_2: f64 = 1.438_776_877;
/// Adapting luminance
/// https://en.wikipedia.org/wiki/CIECAM02#Parameter_decision_table
/// https://en.wikipedia.org/wiki/SRGB#Viewing_environment
const L_A: f64 = 0.20 * 80.;
/// Surround factor
const F: f64 = 1.;
#[derive(Debug)]
enum PPMRaster {
PPM8(Vec<Vec<(u8, u8, u8)>>),
PPM16(Vec<Vec<(u16, u16, u16)>>),
}
#[derive(Debug)]
struct PPM {
width: usize,
height: usize,
maxval: u16,
raster: PPMRaster,
}
impl PPM {
fn write(&self, mut file: File) -> Result<(), io::Error> {
file.write_all(&['P' as u8, '6' as u8, '\n' as u8])?;
file.write_all(self.width.to_string().as_bytes())?;
file.write_all(&[' ' as u8])?;
file.write_all(self.height.to_string().as_bytes())?;
file.write_all(&['\n' as u8])?;
file.write_all(self.maxval.to_string().as_bytes())?;
file.write_all(&['\n' as u8])?;
let mut handle: BufWriter<File> = BufWriter::with_capacity(
match self.maxval {
0..256 => self.width * 3,
_ => self.width * 6,
},
file,
);
for row in 0..self.height {
for column in 0..self.width {
match &self.raster {
PPMRaster::PPM8(pixels) => {
handle.write_all(&[
pixels[row][column].0,
pixels[row][column].1,
pixels[row][column].2,
])?;
}
PPMRaster::PPM16(pixels) => {
handle.write_all(&pixels[row][column].0.to_be_bytes())?;
handle.write_all(&pixels[row][column].1.to_be_bytes())?;
handle.write_all(&pixels[row][column].2.to_be_bytes())?;
}
}
}
}
handle.flush()?;
Ok(())
}
fn read(mut file: File) -> Result<PPM, Box<dyn Error>> {
fn read_line(file: &mut File) -> Result<Vec<char>, io::Error> {
let mut buf: Vec<char> = Vec::new();
loop {
let mut byte: [u8; 1] = Default::default();
file.read_exact(&mut byte)?;
let chr: char = byte[0] as char;
match chr {
'#' => {
while (byte[0] as char) != '\r' && (byte[0] as char) != '\n' {
match file.read_exact(&mut byte) {
Ok(_) => {}
Err(why) => match why.kind() {
ErrorKind::UnexpectedEof => {
return Ok(buf);
}
_ => {
return Err(why);
}
},
}
}
}
'\t' | '\r' | '\n' | ' ' | '\x0b' | '\x0c' => {
return Ok(buf);
}
_ => {
buf.push(chr);
}
}
}
}
fn parse_number<N: FromStr>(v: Vec<char>) -> Result<N, <N as FromStr>::Err> {
v.into_iter().collect::<String>().parse::<N>()
}
let magic_number: Vec<char> = read_line(&mut file)?;
if magic_number != vec!['P', '6'] {
return Err(format!(
"This program only supports PPM files! (magic number = {:?})",
magic_number
)
.into());
}
let width: usize = parse_number(read_line(&mut file)?)?;
let height: usize = parse_number(read_line(&mut file)?)?;
let maxval: u16 = parse_number(read_line(&mut file)?)?;
let mut raster: PPMRaster;
if maxval < 256 {
raster = PPMRaster::PPM8(Vec::with_capacity(height));
} else {
raster = PPMRaster::PPM16(Vec::with_capacity(height));
}
let mut handle: BufReader<File> = match raster {
PPMRaster::PPM8(_) => BufReader::with_capacity(width * 3, file),
PPMRaster::PPM16(_) => BufReader::with_capacity(width * 6, file),
};
for row in 0..height {
match raster {
PPMRaster::PPM8(ref mut v) => v.push(Vec::with_capacity(width)),
PPMRaster::PPM16(ref mut v) => v.push(Vec::with_capacity(width)),
}
for _ in 0..width {
match raster {
PPMRaster::PPM8(ref mut v) => {
let mut buf: [u8; 3] = Default::default();
handle.read_exact(&mut buf)?;
v[row].push((buf[0], buf[1], buf[2]));
}
PPMRaster::PPM16(ref mut v) => {
let mut buf: [u8; 6] = Default::default();
handle.read_exact(&mut buf)?;
fn to_u16(a: u8, b: u8) -> u16 {
((a as u16) << 8) | (b as u16)
}
v[row].push((
to_u16(buf[0], buf[1]),
to_u16(buf[2], buf[3]),
to_u16(buf[4], buf[5]),
));
}
}
}
}
Ok(PPM {
width,
height,
maxval,
raster,
})
}
}
impl From<&PPM> for Raster<SRgb> {
fn from(value: &PPM) -> Self {
let mut floats: Vec<Vec<SRgb>>;
match &value.raster {
PPMRaster::PPM8(v) => {
floats = Vec::with_capacity(v.len());
for row in 0..v.len() {
floats.push(Vec::with_capacity(v[row].len()));
for pixel in 0..v[row].len() {
floats[row].push(SRgb::from((
f64::from(v[row][pixel].0) / (value.maxval as f64),
f64::from(v[row][pixel].1) / (value.maxval as f64),
f64::from(v[row][pixel].2) / (value.maxval as f64),
)));
}
}
}
PPMRaster::PPM16(v) => {
floats = Vec::with_capacity(v.len());
for row in 0..v.len() {
floats.push(Vec::with_capacity(v[row].len()));
for pixel in 0..v[row].len() {
floats[row].push(SRgb::from((
f64::from(v[row][pixel].0) / (value.maxval as f64),
f64::from(v[row][pixel].1) / (value.maxval as f64),
f64::from(v[row][pixel].2) / (value.maxval as f64),
)));
}
}
}
}
Self(floats)
}
}
impl From<(&Raster<SRgb>, u16)> for PPM {
fn from(value: (&Raster<SRgb>, u16)) -> Self {
let floats: &Vec<Vec<SRgb>> = &value.0.0;
let maxval: u16 = value.1;
PPM {
width: floats[0].len(),
height: floats.len(),
maxval,
raster: match maxval {
0..256 => {
let mut integers: Vec<Vec<(u8, u8, u8)>> = Vec::with_capacity(floats.len());
for row in 0..floats.len() {
integers.push(Vec::with_capacity(floats[row].len()));
for pixel in 0..floats[row].len() {
integers[row].push((
(floats[row][pixel].r * (maxval as f64)).round() as u8,
(floats[row][pixel].g * (maxval as f64)).round() as u8,
(floats[row][pixel].b * (maxval as f64)).round() as u8,
));
}
}
PPMRaster::PPM8(integers)
}
_ => {
let mut integers: Vec<Vec<(u16, u16, u16)>> = Vec::with_capacity(floats.len());
for row in 0..floats.len() {
integers.push(Vec::with_capacity(floats[row].len()));
for pixel in 0..floats[row].len() {
integers[row].push((
(floats[row][pixel].r * (maxval as f64)).round() as u16,
(floats[row][pixel].g * (maxval as f64)).round() as u16,
(floats[row][pixel].b * (maxval as f64)).round() as u16,
));
}
}
PPMRaster::PPM16(integers)
}
},
}
}
}
macro_rules! color {
($color_space:ident { $first_component:ident , $second_component:ident , $third_component:ident }) => {
#[derive(Debug, Clone, Copy)]
struct $color_space {
$first_component: f64,
$second_component: f64,
$third_component: f64,
}
impl From<$color_space> for (f64, f64, f64) {
fn from(value: $color_space) -> Self {
(
value.$first_component,
value.$second_component,
value.$third_component,
)
}
}
impl From<(f64, f64, f64)> for $color_space {
fn from(value: (f64, f64, f64)) -> Self {
Self {
$first_component: value.0,
$second_component: value.1,
$third_component: value.2,
}
}
}
};
}
color! {Xyz { x, y, z }}
color! {Rgb { r, g, b }}
color! {SRgb { r, g, b }}
color! {Lms { l, m, s }}
#[derive(Debug)]
struct Raster<C>(Vec<Vec<C>>);
impl<C> Raster<C> {
fn apply<I, F: Fn(&C) -> I>(&self, function: F) -> Raster<I> {
Raster(
self.0
.iter()
.map(|row| row.iter().map(|pixel| function(pixel)).collect())
.collect(),
)
}
fn convert<I: for<'a> From<&'a C>>(&self) -> Raster<I> {
self.apply(|pixel| pixel.into())
}
}
/// https://en.wikipedia.org/wiki/SRGB#Transfer_function_(%22gamma%22)
impl From<&SRgb> for Rgb {
fn from(value: &SRgb) -> Self {
fn transfer(channel: f64) -> f64 {
if channel <= 0.04045 {
channel / 12.92
} else {
((channel + 0.055) / 1.055).powf(2.4)
}
}
Self {
r: transfer(value.r),
g: transfer(value.g),
b: transfer(value.b),
}
}
}
/// https://en.wikipedia.org/wiki/SRGB#Transfer_function_(%22gamma%22)
impl From<&Rgb> for SRgb {
fn from(value: &Rgb) -> Self {
fn inverse_transfer(channel: f64) -> f64 {
if channel < 0. {
-inverse_transfer(-channel)
} else if channel <= 0.0031308 {
12.92 * channel
} else {
1.055 * channel.powf(1. / 2.4) - 0.055
}
}
Self {
r: inverse_transfer(value.r),
g: inverse_transfer(value.g),
b: inverse_transfer(value.b),
}
}
}
impl From<&Rgb> for Xyz {
fn from(value: &Rgb) -> Self {
Self {
x: 0.4124 * value.r + 0.3576 * value.g + 0.1805 * value.b,
y: 0.2126 * value.r + 0.7152 * value.g + 0.0722 * value.b,
z: 0.0193 * value.r + 0.1192 * value.g + 0.9505 * value.b,
}
}
}
impl From<&Xyz> for Lms {
fn from(value: &Xyz) -> Self {
Self {
l: 0.4002 * value.x + 0.7076 * value.y + -0.0808 * value.z,
m: -0.2263 * value.x + 1.1653 * value.y + 0.0457 * value.z,
s: 0.9182 * value.z,
}
}
}
impl From<&Lms> for Rgb {
fn from(value: &Lms) -> Self {
Self {
r: 5.47250449 * value.l + -4.64219699 * value.m + 0.16956890 * value.s,
g: -1.12470958 * value.l + 2.29262899 * value.m + -0.16786338 * value.s,
b: 0.02992745 * value.l + -0.19325300 * value.m + 1.16341292 * value.s,
}
}
}
fn chromatic_adaption(pixel: &Lms, source: &Lms, target: &Lms) -> Lms {
let d: f64 = F * (1. - (1. / 3.6) * f64::exp((-L_A - 42.) / 92.));
Lms {
l: ((target.l / source.l) * d + 1. - d) * pixel.l,
m: ((target.m / source.m) * d + 1. - d) * pixel.m,
s: ((target.s / source.s) * d + 1. - d) * pixel.s,
}
}
/// Perform chromatic adaption on an LMS image
/// Takes source and target illuminants in LMS form as inputs
/// https://en.wikipedia.org/wiki/CIECAM02#CAT02
fn chromatic_adaption_raster(lms: &Raster<Lms>, source: &Lms, target: &Lms) -> Raster<Lms> {
lms.apply(|pixel| chromatic_adaption(pixel, source, target))
}
/// Compute LMS coordinates coordinate of the D illuminant of the given temperature (in K)
/// Color temperature is rectified (e.g. 6500K -> 6503.51K).
/// Standard value of 1 for Y is used
fn standard_illuminant_d(temperature: f64) -> Result<Lms, &'static str> {
// Adjust temperature (you know, Planck's constant sometime changes)
let t: f64 = temperature * (C_2 / 1.4380);
// Compute xy (CIE 1931) coordinates of the illuminant
let x_d: f64;
if temperature < 1667. {
return Err("No D illuminant below 1667K.");
} else if temperature <= 4000. {
// /!\ Planckian locus approximation
x_d = -0.2661239 * (1e9 / t.powf(3.)) - 0.2343589 * (1e6 / t.powf(2.))
+ 0.8776956 * (1e3 / t)
+ 0.179910
} else if temperature <= 7000. {
x_d = 0.244063 + (0.09911 * (1e3 / t)) + (2.9678 * (1e6 / t.powf(2.)))
- (4.6070 * (1e9 / t.powf(3.)));
} else if temperature <= 25000. {
x_d = 0.237040 + (0.24748 * (1e3 / t)) + (1.9018 * (1e6 / t.powf(2.)))
- (2.0064 * (1e9 / t.powf(3.)));
} else {
return Err("No D illuminant above 25000K");
}
let y_d: f64;
if temperature <= 2222. {
y_d = -1.1063814 * x_d.powf(3.) - 1.34811020 * x_d.powf(2.) + 2.18555832 * x_d - 0.20219683
} else if temperature <= 4000. {
y_d = -0.9549476 * x_d.powf(3.) - 1.37418593 * x_d.powf(2.) + 2.09137015 * x_d - 0.16748867;
} else {
y_d = (-3.000 * (x_d.powf(2.))) + (2.870 * x_d) - 0.275;
}
// Assuming Y = 1, convert xy (to xyY) to XYZ
let xyz: Xyz = Xyz {
x: (1. / y_d) * x_d,
y: 1.,
z: (1. / y_d) * (1. - x_d - y_d),
};
// Convert to LMS
let lms: Lms = Lms::from(&xyz);
Ok(lms)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut args: Args = std::env::args();
args.next();
let input_path: &str = &args
.next()
.ok_or("First argument must be the path to the input file")?;
let output_path: &str = &args
.next()
.ok_or("Second argument must be the path to the output file")?;
// Target color temperature
let target_illuminant: Lms = standard_illuminant_d(
args.next()
.map(|temperature| temperature.parse::<f64>().unwrap_or(4000.))
.unwrap_or(4000.),
)?;
// sRGB encoding illuminant
let source_illuminant: Lms = standard_illuminant_d(
args.next()
.map(|temperature| temperature.parse::<f64>().unwrap_or(6500.))
.unwrap_or(6500.),
)?;
let path: &Path = Path::new(input_path);
let file: File = File::open(&path)?;
let ppm: PPM = PPM::read(file)?;
let s_rgb_raster: Raster<SRgb> = Raster::from(&ppm);
// Multiple functions version
// Caution: memory intensive!
/*
let rgb_raster: Raster<Rgb> = s_rgb_raster.convert::<Rgb>();
let xyz_raster: Raster<Xyz> = rgb_raster.convert::<Xyz>();
let lms_raster: Raster<Lms> = xyz_raster.convert::<Lms>();
let lms_raster_adapt: Raster<Lms> =
chromatic_adaption_raster(&lms_raster, &source_illuminant, &target_illuminant);
let rgb_raster_adapt: Raster<Rgb> = lms_raster_adapt.convert::<Rgb>();
let s_rgb_raster_adapt: Raster<SRgb> = rgb_raster_adapt.convert::<SRgb>();
*/
// Single function version
let s_rgb_raster_adapt: Raster<SRgb> = s_rgb_raster.apply(|pixel| {
SRgb::from(&Rgb::from(&chromatic_adaption(
&Lms::from(&Xyz::from(&Rgb::from(pixel))),
&source_illuminant,
&target_illuminant,
)))
});
let output: PPM = PPM::from((&s_rgb_raster_adapt, ppm.maxval));
output.write(File::create(Path::new(output_path))?)?;
Ok(())
}
|
is this #0000ff
yes it is!
is it srgb
i dont know i looked up "0000ff" and screenshotted the first result
this is awesome i love it
thank youuuu :33 mreaow
post a comment