-
-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathimage_processing.rs
More file actions
2775 lines (2409 loc) · 89.7 KB
/
image_processing.rs
File metadata and controls
2775 lines (2409 loc) · 89.7 KB
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
999
1000
use bytemuck::{Pod, Zeroable};
use glam::{Mat3, Vec2, Vec3};
use image::{DynamicImage, GenericImageView, Rgb32FImage, Rgba};
use imageproc::geometric_transformations::{Interpolation, rotate_about_center};
use nalgebra::{Matrix3 as NaMatrix3, Vector3 as NaVector3};
use rawler::decoders::Orientation;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::json;
use std::f32::consts::PI;
use std::sync::Arc;
pub use crate::gpu_processing::{
RenderRequest, get_or_init_gpu_context, process_and_get_dynamic_image,
};
use crate::{AppState, mask_generation::MaskDefinition};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ImageMetadata {
pub version: u32,
pub rating: u8,
pub adjustments: Value,
#[serde(default)]
pub tags: Option<Vec<String>>,
}
impl Default for ImageMetadata {
fn default() -> Self {
ImageMetadata {
version: 1,
rating: 0,
adjustments: Value::Null,
tags: None,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Crop {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct GeometryParams {
pub distortion: f32,
pub vertical: f32,
pub horizontal: f32,
pub rotate: f32,
pub aspect: f32,
pub scale: f32,
pub x_offset: f32,
pub y_offset: f32,
pub lens_distortion_amount: f32,
pub lens_vignette_amount: f32,
pub lens_tca_amount: f32,
pub lens_distortion_enabled: bool,
pub lens_tca_enabled: bool,
pub lens_vignette_enabled: bool,
pub lens_dist_k1: f32,
pub lens_dist_k2: f32,
pub lens_dist_k3: f32,
pub lens_model: u32,
pub tca_vr: f32,
pub tca_vb: f32,
pub vig_k1: f32,
pub vig_k2: f32,
pub vig_k3: f32,
}
impl Default for GeometryParams {
fn default() -> Self {
Self {
distortion: 0.0,
vertical: 0.0,
horizontal: 0.0,
rotate: 0.0,
aspect: 0.0,
scale: 100.0,
x_offset: 0.0,
y_offset: 0.0,
lens_distortion_amount: 1.0,
lens_vignette_amount: 1.0,
lens_tca_amount: 1.0,
lens_distortion_enabled: true,
lens_tca_enabled: true,
lens_vignette_enabled: true,
lens_dist_k1: 0.0,
lens_dist_k2: 0.0,
lens_dist_k3: 0.0,
lens_model: 0,
tca_vr: 1.0,
tca_vb: 1.0,
vig_k1: 0.0,
vig_k2: 0.0,
vig_k3: 0.0,
}
}
}
pub fn get_geometry_params_from_json(adjustments: &serde_json::Value) -> GeometryParams {
let lens_params = adjustments
.get("lensDistortionParams")
.and_then(|v| v.as_object());
GeometryParams {
distortion: adjustments["transformDistortion"].as_f64().unwrap_or(0.0) as f32,
vertical: adjustments["transformVertical"].as_f64().unwrap_or(0.0) as f32,
horizontal: adjustments["transformHorizontal"].as_f64().unwrap_or(0.0) as f32,
rotate: adjustments["transformRotate"].as_f64().unwrap_or(0.0) as f32,
aspect: adjustments["transformAspect"].as_f64().unwrap_or(0.0) as f32,
scale: adjustments["transformScale"].as_f64().unwrap_or(100.0) as f32,
x_offset: adjustments["transformXOffset"].as_f64().unwrap_or(0.0) as f32,
y_offset: adjustments["transformYOffset"].as_f64().unwrap_or(0.0) as f32,
lens_distortion_amount: adjustments["lensDistortionAmount"]
.as_f64()
.unwrap_or(100.0) as f32
/ 100.0,
lens_vignette_amount: adjustments["lensVignetteAmount"].as_f64().unwrap_or(100.0) as f32
/ 100.0,
lens_tca_amount: adjustments["lensTcaAmount"].as_f64().unwrap_or(100.0) as f32 / 100.0,
lens_distortion_enabled: adjustments["lensDistortionEnabled"]
.as_bool()
.unwrap_or(true),
lens_tca_enabled: adjustments["lensTcaEnabled"].as_bool().unwrap_or(true),
lens_vignette_enabled: adjustments["lensVignetteEnabled"].as_bool().unwrap_or(true),
lens_dist_k1: lens_params
.and_then(|p| p.get("k1").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
lens_dist_k2: lens_params
.and_then(|p| p.get("k2").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
lens_dist_k3: lens_params
.and_then(|p| p.get("k3").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
lens_model: lens_params
.and_then(|p| p.get("model").and_then(|m| m.as_u64()))
.unwrap_or(0) as u32,
tca_vr: lens_params
.and_then(|p| p.get("tca_vr").and_then(|k| k.as_f64()))
.unwrap_or(1.0) as f32,
tca_vb: lens_params
.and_then(|p| p.get("tca_vb").and_then(|k| k.as_f64()))
.unwrap_or(1.0) as f32,
vig_k1: lens_params
.and_then(|p| p.get("vig_k1").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
vig_k2: lens_params
.and_then(|p| p.get("vig_k2").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
vig_k3: lens_params
.and_then(|p| p.get("vig_k3").and_then(|k| k.as_f64()))
.unwrap_or(0.0) as f32,
}
}
pub fn downscale_f32_image(image: &DynamicImage, nwidth: u32, nheight: u32) -> DynamicImage {
let (width, height) = image.dimensions();
if nwidth == 0 || nheight == 0 {
return image.clone();
}
if nwidth >= width && nheight >= height {
return image.clone();
}
let ratio = (nwidth as f32 / width as f32).min(nheight as f32 / height as f32);
let new_w = (width as f32 * ratio).round() as u32;
let new_h = (height as f32 * ratio).round() as u32;
if new_w == 0 || new_h == 0 {
return image.clone();
}
let img = image.to_rgb32f();
let src: &[f32] = img.as_flat_samples().samples;
let x_ratio = width as f32 / new_w as f32;
let y_ratio = height as f32 / new_h as f32;
let mut out_buf = vec![0.0f32; (new_w * new_h * 3) as usize];
out_buf
.par_chunks_exact_mut(new_w as usize * 3)
.enumerate()
.for_each(|(y_out, row)| {
let y_start = (y_out as f32 * y_ratio).floor() as usize;
let y_end = (((y_out + 1) as f32 * y_ratio).ceil() as usize).min(height as usize);
for x_out in 0..new_w as usize {
let x_start = (x_out as f32 * x_ratio).floor() as usize;
let x_end = (((x_out + 1) as f32 * x_ratio).ceil() as usize).min(width as usize);
let mut r_sum = 0.0f32;
let mut g_sum = 0.0f32;
let mut b_sum = 0.0f32;
let mut count = 0u32;
for y_in in y_start..y_end {
let row_offset = y_in * width as usize * 3;
for x_in in x_start..x_end {
let idx = row_offset + x_in * 3;
r_sum += src[idx];
g_sum += src[idx + 1];
b_sum += src[idx + 2];
count += 1;
}
}
if count > 0 {
let n = count as f32;
let out_idx = x_out * 3;
row[out_idx] = r_sum / n;
row[out_idx + 1] = g_sum / n;
row[out_idx + 2] = b_sum / n;
}
}
});
let out = Rgb32FImage::from_raw(new_w, new_h, out_buf).expect("buffer size mismatch");
DynamicImage::ImageRgb32F(out)
}
#[inline(always)]
fn interpolate_pixel(
src_raw: &[f32],
src_width: usize,
src_height: usize,
x: f32,
y: f32,
pixel_out: &mut [f32],
) {
if x.is_nan()
|| y.is_nan()
|| x < 0.0
|| y < 0.0
|| x >= (src_width as f32 - 1.0)
|| y >= (src_height as f32 - 1.0)
{
return;
}
let x0 = x.floor() as usize;
let y0 = y.floor() as usize;
let wx = x - x0 as f32;
let wy = y - y0 as f32;
let one_minus_wx = 1.0 - wx;
let one_minus_wy = 1.0 - wy;
let stride = src_width * 3;
let idx_row0 = y0 * stride;
let idx_row1 = idx_row0 + stride;
let idx_p00 = idx_row0 + x0 * 3;
unsafe {
let p00 = src_raw.get_unchecked(idx_p00..idx_p00 + 3);
let p10 = src_raw.get_unchecked(idx_p00 + 3..idx_p00 + 6);
let p01 = src_raw.get_unchecked(idx_row1 + x0 * 3..idx_row1 + x0 * 3 + 3);
let p11 = src_raw.get_unchecked(idx_row1 + x0 * 3 + 3..idx_row1 + x0 * 3 + 6);
let top_r = p00[0] * one_minus_wx + p10[0] * wx;
let top_g = p00[1] * one_minus_wx + p10[1] * wx;
let top_b = p00[2] * one_minus_wx + p10[2] * wx;
let bot_r = p01[0] * one_minus_wx + p11[0] * wx;
let bot_g = p01[1] * one_minus_wx + p11[1] * wx;
let bot_b = p01[2] * one_minus_wx + p11[2] * wx;
pixel_out[0] = top_r * one_minus_wy + bot_r * wy;
pixel_out[1] = top_g * one_minus_wy + bot_g * wy;
pixel_out[2] = top_b * one_minus_wy + bot_b * wy;
}
}
fn build_transform_matrices(
params: &GeometryParams,
width: f32,
height: f32,
) -> (NaMatrix3<f32>, f32, f32, f64) {
let cx = width / 2.0;
let cy = height / 2.0;
let ref_dim = 2000.0;
let p_vert = (params.vertical / 100000.0) * (ref_dim / height);
let p_horiz = (-params.horizontal / 100000.0) * (ref_dim / width);
let theta = params.rotate.to_radians();
let aspect_factor = if params.aspect >= 0.0 {
1.0 + params.aspect / 100.0
} else {
1.0 / (1.0 + params.aspect.abs() / 100.0)
};
let scale_factor = params.scale / 100.0;
let off_x = (params.x_offset / 100.0) * width;
let off_y = (params.y_offset / 100.0) * height;
let t_center = NaMatrix3::new(1.0, 0.0, cx, 0.0, 1.0, cy, 0.0, 0.0, 1.0);
let t_uncenter = NaMatrix3::new(1.0, 0.0, -cx, 0.0, 1.0, -cy, 0.0, 0.0, 1.0);
let m_perspective = NaMatrix3::new(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, p_horiz, p_vert, 1.0);
let (sin_t, cos_t) = theta.sin_cos();
let m_rotate = NaMatrix3::new(cos_t, -sin_t, 0.0, sin_t, cos_t, 0.0, 0.0, 0.0, 1.0);
let m_scale = NaMatrix3::new(
scale_factor * aspect_factor,
0.0,
0.0,
0.0,
scale_factor,
0.0,
0.0,
0.0,
1.0,
);
let m_offset = NaMatrix3::new(1.0, 0.0, off_x, 0.0, 1.0, off_y, 0.0, 0.0, 1.0);
let forward = t_center * m_offset * m_perspective * m_rotate * m_scale * t_uncenter;
let half_diagonal =
((width as f64 * width as f64 + height as f64 * height as f64).sqrt()) / 2.0;
(forward, cx, cy, half_diagonal)
}
struct TcaContext<'a> {
src_raw: &'a [f32],
src_width: usize,
src_height: usize,
cx: f32,
cy: f32,
}
#[inline(always)]
fn interpolate_pixel_with_tca(
tca: &TcaContext,
base_x: f32,
base_y: f32,
vr: f32,
vb: f32,
pixel_out: &mut [f32],
) {
let src_raw = tca.src_raw;
let src_width = tca.src_width;
let src_height = tca.src_height;
let cx = tca.cx;
let cy = tca.cy;
let gx = base_x;
let gy = base_y;
let rx = cx + (base_x - cx) * vr;
let ry = cy + (base_y - cy) * vr;
let bx = cx + (base_x - cx) * vb;
let by = cy + (base_y - cy) * vb;
let sample_channel = |target_x: f32, target_y: f32, channel_idx: usize| -> f32 {
if target_x.is_nan() || target_y.is_nan() {
return 0.0;
}
let x_clamped = target_x.clamp(0.0, src_width as f32 - 1.0);
let y_clamped = target_y.clamp(0.0, src_height as f32 - 1.0);
let mut x0 = x_clamped.floor() as usize;
let mut y0 = y_clamped.floor() as usize;
if x0 >= src_width - 1 {
x0 = src_width.saturating_sub(2);
}
if y0 >= src_height - 1 {
y0 = src_height.saturating_sub(2);
}
let wx = x_clamped - x0 as f32;
let wy = y_clamped - y0 as f32;
let one_minus_wx = 1.0 - wx;
let one_minus_wy = 1.0 - wy;
let stride = src_width * 3;
let idx_row0 = y0 * stride;
let idx_row1 = idx_row0 + stride;
let idx_p00 = idx_row0 + x0 * 3 + channel_idx;
unsafe {
let p00 = *src_raw.get_unchecked(idx_p00);
let p10 = *src_raw.get_unchecked(idx_p00 + 3);
let p01 = *src_raw.get_unchecked(idx_row1 + x0 * 3 + channel_idx);
let p11 = *src_raw.get_unchecked(idx_row1 + x0 * 3 + 3 + channel_idx);
let top = p00 * one_minus_wx + p10 * wx;
let bot = p01 * one_minus_wx + p11 * wx;
top * one_minus_wy + bot * wy
}
};
pixel_out[0] = sample_channel(rx, ry, 0);
pixel_out[1] = sample_channel(gx, gy, 1);
pixel_out[2] = sample_channel(bx, by, 2);
}
fn solve_generic_distortion_inv(r_target: f64, k_scaled: f64) -> f64 {
if k_scaled.abs() < 1e-9 {
return r_target;
}
let mut r = r_target;
for _ in 0..10 {
let r2 = r * r;
let val = k_scaled * r2 * r + r - r_target;
let slope = 3.0 * k_scaled * r2 + 1.0;
if slope.abs() < 1e-9 {
break;
}
let delta = val / slope;
r -= delta;
if delta.abs() < 1e-6 {
break;
}
}
r
}
fn compute_lens_auto_crop_scale(params: &GeometryParams, width: f32, height: f32) -> f64 {
let cx = (width / 2.0) as f64;
let cy = (height / 2.0) as f64;
let half_diagonal = (cx * cx + cy * cy).sqrt();
let max_radius_sq_inv = 1.0 / (cx * cx + cy * cy);
let lk1 = params.lens_dist_k1 as f64;
let lk2 = params.lens_dist_k2 as f64;
let lk3 = params.lens_dist_k3 as f64;
let lens_dist_amt = (params.lens_distortion_amount as f64) * 2.5;
let k_distortion = (params.distortion as f64 / 100.0) * 2.5;
let has_lens_correction = params.lens_distortion_enabled
&& (lk1.abs() > 1e-6 || lk2.abs() > 1e-6 || lk3.abs() > 1e-6);
let is_ptlens = params.lens_model == 1;
let sample_points: [(f64, f64); 8] = [
(cx, 0.0),
(cx, height as f64),
(0.0, cy),
(width as f64, cy),
(0.0, 0.0),
(width as f64, 0.0),
(0.0, height as f64),
(width as f64, height as f64),
];
let mut max_scale: f64 = 1.0;
for &(px, py) in &sample_points {
let dx = px - cx;
let dy = py - cy;
let ru = (dx * dx + dy * dy).sqrt();
if ru < 1e-6 {
continue;
}
let mut mapped_dx = dx;
let mut mapped_dy = dy;
if has_lens_correction {
let ru_norm = ru / half_diagonal;
let ru_norm2 = ru_norm * ru_norm;
let rd_norm = if is_ptlens {
let a = lk1;
let b = lk2;
let c = lk3;
let d = 1.0 - a - b - c;
ru_norm * (a * ru_norm2 * ru_norm + b * ru_norm2 + c * ru_norm + d)
} else {
ru_norm
* (1.0
+ lk1 * ru_norm2
+ lk2 * (ru_norm2 * ru_norm2)
+ lk3 * (ru_norm2 * ru_norm2 * ru_norm2))
};
let effective_r_norm = ru_norm + (rd_norm - ru_norm) * lens_dist_amt;
let scale = effective_r_norm / ru_norm;
mapped_dx *= scale;
mapped_dy *= scale;
}
if k_distortion.abs() > 1e-5 {
let r2_norm = (mapped_dx * mapped_dx + mapped_dy * mapped_dy) * max_radius_sq_inv;
let f = 1.0 + k_distortion * r2_norm;
mapped_dx *= f;
mapped_dy *= f;
}
let mapped_ru = (mapped_dx * mapped_dx + mapped_dy * mapped_dy).sqrt();
let scale = mapped_ru / ru;
if scale > max_scale {
max_scale = scale;
}
}
if max_scale > 1.0 {
max_scale * 1.002
} else {
max_scale
}
}
pub fn warp_image_geometry(image: &DynamicImage, params: GeometryParams) -> DynamicImage {
let src_img = image.to_rgb32f();
let (width, height) = src_img.dimensions();
let mut out_buffer = vec![0.0f32; (width * height * 3) as usize];
let (forward_transform, cx, cy, half_diagonal) =
build_transform_matrices(¶ms, width as f32, height as f32);
let inv = forward_transform
.try_inverse()
.unwrap_or(NaMatrix3::identity());
let step_vec_x = NaVector3::new(inv[(0, 0)], inv[(1, 0)], inv[(2, 0)]);
let step_vec_y = NaVector3::new(inv[(0, 1)], inv[(1, 1)], inv[(2, 1)]);
let origin_vec = NaVector3::new(inv[(0, 2)], inv[(1, 2)], inv[(2, 2)]);
let max_radius_sq_inv = 1.0 / ((cx * cx + cy * cy) as f64);
let hd = half_diagonal;
let k_distortion = (params.distortion as f64 / 100.0) * 2.5;
let lk1 = params.lens_dist_k1 as f64;
let lk2 = params.lens_dist_k2 as f64;
let lk3 = params.lens_dist_k3 as f64;
let lens_dist_amt = (params.lens_distortion_amount as f64) * 2.5;
let has_lens_correction = params.lens_distortion_enabled
&& (lk1.abs() > 1e-6 || lk2.abs() > 1e-6 || lk3.abs() > 1e-6);
let is_ptlens = params.lens_model == 1;
let auto_crop_scale = if has_lens_correction || k_distortion.abs() > 1e-5 {
compute_lens_auto_crop_scale(¶ms, width as f32, height as f32) as f32
} else {
1.0
};
let vr = if (params.tca_vr - 1.0).abs() > 1e-5 {
params.tca_vr + (1.0 - params.tca_vr) * (1.0 - params.lens_tca_amount)
} else {
1.0
};
let vb = if (params.tca_vb - 1.0).abs() > 1e-5 {
params.tca_vb + (1.0 - params.tca_vb) * (1.0 - params.lens_tca_amount)
} else {
1.0
};
let has_tca = params.lens_tca_enabled && ((vr - 1.0).abs() > 1e-5 || (vb - 1.0).abs() > 1e-5);
let vk1 = params.vig_k1 as f64;
let vk2 = params.vig_k2 as f64;
let vk3 = params.vig_k3 as f64;
let lens_vig_amt = (params.lens_vignette_amount as f64) * 0.8;
let has_vignetting = params.lens_vignette_enabled
&& (vk1.abs() > 1e-6 || vk2.abs() > 1e-6 || vk3.abs() > 1e-6)
&& lens_vig_amt > 0.01;
let src_raw = src_img.as_raw();
let width_usize = width as usize;
let height_usize = height as usize;
let tca_ctx = TcaContext {
src_raw,
src_width: width_usize,
src_height: height_usize,
cx,
cy,
};
out_buffer
.par_chunks_exact_mut(width_usize * 3)
.enumerate()
.for_each(|(y, row_pixel_data)| {
let y_f = y as f32;
let mut current_vec = origin_vec + (step_vec_y * y_f);
for pixel in row_pixel_data.chunks_exact_mut(3) {
if current_vec.z.abs() > 1e-6 {
let inv_z = 1.0 / current_vec.z;
let mut src_x = current_vec.x * inv_z;
let mut src_y = current_vec.y * inv_z;
if auto_crop_scale > 1.0 {
src_x = cx + (src_x - cx) / auto_crop_scale;
src_y = cy + (src_y - cy) / auto_crop_scale;
}
if has_lens_correction {
let dx = (src_x - cx) as f64;
let dy = (src_y - cy) as f64;
let ru = (dx * dx + dy * dy).sqrt();
if ru > 1e-6 {
let ru_norm = ru / hd;
let ru_norm2 = ru_norm * ru_norm;
let rd_norm = if is_ptlens {
let a = lk1;
let b = lk2;
let c = lk3;
let d = 1.0 - a - b - c;
ru_norm * (a * ru_norm2 * ru_norm + b * ru_norm2 + c * ru_norm + d)
} else {
ru_norm
* (1.0
+ lk1 * ru_norm2
+ lk2 * (ru_norm2 * ru_norm2)
+ lk3 * (ru_norm2 * ru_norm2 * ru_norm2))
};
let effective_r_norm = ru_norm + (rd_norm - ru_norm) * lens_dist_amt;
let scale = effective_r_norm / ru_norm;
src_x = cx + (dx * scale) as f32;
src_y = cy + (dy * scale) as f32;
}
}
if k_distortion.abs() > 1e-5 {
let dx = (src_x - cx) as f64;
let dy = (src_y - cy) as f64;
let r2_norm = (dx * dx + dy * dy) * max_radius_sq_inv;
let f = 1.0 + k_distortion * r2_norm;
src_x = cx + (dx * f) as f32;
src_y = cy + (dy * f) as f32;
}
if has_tca {
interpolate_pixel_with_tca(&tca_ctx, src_x, src_y, vr, vb, pixel);
} else {
interpolate_pixel(src_raw, width_usize, height_usize, src_x, src_y, pixel);
}
if has_vignetting {
let dx = (src_x - cx) as f64;
let dy = (src_y - cy) as f64;
let ru = (dx * dx + dy * dy).sqrt();
let ru_norm = ru / hd;
let ru_norm2 = ru_norm * ru_norm;
let v_factor = 1.0
+ vk1 * ru_norm2
+ vk2 * (ru_norm2 * ru_norm2)
+ vk3 * (ru_norm2 * ru_norm2 * ru_norm2);
if v_factor > 1e-6 {
let correction_gain = 1.0 / v_factor;
let final_gain = 1.0 + (correction_gain - 1.0) * lens_vig_amt;
pixel[0] *= final_gain as f32;
pixel[1] *= final_gain as f32;
pixel[2] *= final_gain as f32;
}
}
}
current_vec += step_vec_x;
}
});
let out_img = Rgb32FImage::from_vec(width, height, out_buffer).unwrap();
DynamicImage::ImageRgb32F(out_img)
}
pub fn unwarp_image_geometry(warped_image: &DynamicImage, params: GeometryParams) -> DynamicImage {
let src_img = warped_image.to_rgb32f();
let (width, height) = src_img.dimensions();
let mut out_buffer = vec![0.0f32; (width * height * 3) as usize];
let (forward_transform, cx, cy, half_diagonal) =
build_transform_matrices(¶ms, width as f32, height as f32);
let max_radius_sq_inv = 1.0 / ((cx * cx + cy * cy) as f64);
let hd = half_diagonal;
let k_distortion = (params.distortion as f64 / 100.0) * 2.5;
let lk1 = params.lens_dist_k1 as f64;
let lk2 = params.lens_dist_k2 as f64;
let lk3 = params.lens_dist_k3 as f64;
let lens_dist_amt = (params.lens_distortion_amount as f64) * 2.5;
let has_lens_correction = params.lens_distortion_enabled
&& (lk1.abs() > 1e-6 || lk2.abs() > 1e-6 || lk3.abs() > 1e-6);
let is_ptlens = params.lens_model == 1;
let auto_crop_scale = if has_lens_correction || k_distortion.abs() > 1e-5 {
compute_lens_auto_crop_scale(¶ms, width as f32, height as f32) as f32
} else {
1.0
};
let src_raw = src_img.as_raw();
let width_usize = width as usize;
let height_usize = height as usize;
out_buffer
.par_chunks_exact_mut(width_usize * 3)
.enumerate()
.for_each(|(y, row_pixel_data)| {
let y_f = y as f32;
for (x, pixel) in row_pixel_data.chunks_exact_mut(3).enumerate() {
let x_f = x as f32;
let mut current_x = x_f;
let mut current_y = y_f;
if k_distortion.abs() > 1e-5 {
let dx = (current_x - cx) as f64;
let dy = (current_y - cy) as f64;
let r_distorted = (dx * dx + dy * dy).sqrt();
if r_distorted > 1e-6 {
let k_effective = k_distortion * max_radius_sq_inv;
let r_straight = solve_generic_distortion_inv(r_distorted, k_effective);
let scale = r_straight / r_distorted;
current_x = cx + (dx * scale) as f32;
current_y = cy + (dy * scale) as f32;
}
}
if has_lens_correction {
let dx = (current_x - cx) as f64;
let dy = (current_y - cy) as f64;
let rd = (dx * dx + dy * dy).sqrt();
if rd > 1e-6 {
let mut ru = rd;
for _ in 0..8 {
let ru_norm = ru / hd;
let ru_norm2 = ru_norm * ru_norm;
let (f_val, f_prime) = if is_ptlens {
let a = lk1;
let b = lk2;
let c = lk3;
let d = 1.0 - a - b - c;
let poly = a * ru_norm2 * ru_norm + b * ru_norm2 + c * ru_norm + d;
let val = ru * poly;
let prime = 4.0 * a * ru_norm2 * ru_norm
+ 3.0 * b * ru_norm2
+ 2.0 * c * ru_norm
+ d;
(val, prime)
} else {
let poly = 1.0
+ lk1 * ru_norm2
+ lk2 * (ru_norm2 * ru_norm2)
+ lk3 * (ru_norm2 * ru_norm2 * ru_norm2);
let val = ru * poly;
let poly_prime = 2.0 * lk1 * ru_norm
+ 4.0 * lk2 * ru_norm2 * ru_norm
+ 6.0 * lk3 * (ru_norm2 * ru_norm2) * ru_norm;
let prime = poly + ru_norm * poly_prime;
(val, prime)
};
let g_val = ru + (f_val - ru) * lens_dist_amt - rd;
let g_prime = 1.0 + (f_prime - 1.0) * lens_dist_amt;
if g_prime.abs() < 1e-7 {
break;
}
let delta = g_val / g_prime;
ru -= delta;
if delta.abs() < 1e-4 {
break;
}
}
let scale = ru / rd;
current_x = cx + (dx * scale) as f32;
current_y = cy + (dy * scale) as f32;
}
}
if auto_crop_scale > 1.0 {
current_x = cx + (current_x - cx) * auto_crop_scale;
current_y = cy + (current_y - cy) * auto_crop_scale;
}
let target_vec = forward_transform * NaVector3::new(current_x, current_y, 1.0);
if target_vec.z.abs() > 1e-6 {
let inv_z = 1.0 / target_vec.z;
let src_x = target_vec.x * inv_z;
let src_y = target_vec.y * inv_z;
interpolate_pixel(src_raw, width_usize, height_usize, src_x, src_y, pixel);
}
}
});
let out_img = Rgb32FImage::from_vec(width, height, out_buffer).unwrap();
DynamicImage::ImageRgb32F(out_img)
}
pub fn apply_cpu_default_raw_processing(image: &mut DynamicImage) {
let mut f32_image = image.to_rgb32f();
const GAMMA: f32 = 2.38;
const INV_GAMMA: f32 = 1.0 / GAMMA;
const CONTRAST: f32 = 1.28;
f32_image.par_chunks_mut(3).for_each(|pixel_chunk| {
let r_gamma = pixel_chunk[0].powf(INV_GAMMA);
let g_gamma = pixel_chunk[1].powf(INV_GAMMA);
let b_gamma = pixel_chunk[2].powf(INV_GAMMA);
let r_contrast = (r_gamma - 0.5) * CONTRAST + 0.5;
let g_contrast = (g_gamma - 0.5) * CONTRAST + 0.5;
let b_contrast = (b_gamma - 0.5) * CONTRAST + 0.5;
pixel_chunk[0] = r_contrast.clamp(0.0, 1.0);
pixel_chunk[1] = g_contrast.clamp(0.0, 1.0);
pixel_chunk[2] = b_contrast.clamp(0.0, 1.0);
});
*image = DynamicImage::ImageRgb32F(f32_image);
}
pub fn apply_orientation(image: DynamicImage, orientation: Orientation) -> DynamicImage {
match orientation {
Orientation::Normal | Orientation::Unknown => image,
Orientation::HorizontalFlip => image.fliph(),
Orientation::Rotate180 => image.rotate180(),
Orientation::VerticalFlip => image.flipv(),
Orientation::Transpose => image.rotate90().flipv(),
Orientation::Rotate90 => image.rotate90(),
Orientation::Transverse => image.rotate90().fliph(),
Orientation::Rotate270 => image.rotate270(),
}
}
pub fn apply_coarse_rotation(image: DynamicImage, orientation_steps: u8) -> DynamicImage {
match orientation_steps {
1 => image.rotate90(),
2 => image.rotate180(),
3 => image.rotate270(),
_ => image,
}
}
pub fn apply_rotation(image: &DynamicImage, rotation_degrees: f32) -> DynamicImage {
if rotation_degrees % 360.0 == 0.0 {
return image.clone();
}
let rgba_image = image.to_rgba32f();
let rotated = rotate_about_center(
&rgba_image,
rotation_degrees * PI / 180.0,
Interpolation::Bilinear,
Rgba([0.0f32, 0.0, 0.0, 0.0]),
);
DynamicImage::ImageRgba32F(rotated)
}
pub fn apply_crop(mut image: DynamicImage, crop_value: &Value) -> DynamicImage {
if crop_value.is_null() {
return image;
}
if let Ok(crop) = serde_json::from_value::<Crop>(crop_value.clone()) {
let x = crop.x.round() as u32;
let y = crop.y.round() as u32;
let width = crop.width.round() as u32;
let height = crop.height.round() as u32;
if width > 0 && height > 0 {
let (img_w, img_h) = image.dimensions();
if x < img_w && y < img_h {
let new_width = (img_w - x).min(width);
let new_height = (img_h - y).min(height);
if new_width > 0 && new_height > 0 {
image = image.crop_imm(x, y, new_width, new_height);
}
}
}
}
image
}
pub fn is_geometry_identity(params: &GeometryParams) -> bool {
let dist_identity = !params.lens_distortion_enabled
|| ((params.lens_distortion_amount - 1.0).abs() < 1e-4
&& params.lens_dist_k1.abs() < 1e-6
&& params.lens_dist_k2.abs() < 1e-6
&& params.lens_dist_k3.abs() < 1e-6);
let tca_identity = !params.lens_tca_enabled
|| ((params.lens_tca_amount - 1.0).abs() < 1e-4
&& (params.tca_vr - 1.0).abs() < 1e-6
&& (params.tca_vb - 1.0).abs() < 1e-6);
let vig_identity = !params.lens_vignette_enabled
|| ((params.lens_vignette_amount - 1.0).abs() < 1e-4
&& params.vig_k1.abs() < 1e-6
&& params.vig_k2.abs() < 1e-6
&& params.vig_k3.abs() < 1e-6);
params.distortion == 0.0
&& params.vertical == 0.0
&& params.horizontal == 0.0
&& params.rotate == 0.0
&& params.aspect == 0.0
&& params.scale == 100.0
&& params.x_offset == 0.0
&& params.y_offset == 0.0
&& dist_identity
&& tca_identity
&& vig_identity
}
pub fn apply_geometry_warp(image: &DynamicImage, adjustments: &serde_json::Value) -> DynamicImage {
let params = get_geometry_params_from_json(adjustments);
if !is_geometry_identity(¶ms) {
warp_image_geometry(image, params)
} else {
image.clone()
}
}
pub fn apply_unwarp_geometry(
image: &DynamicImage,
adjustments: &serde_json::Value,
) -> DynamicImage {
let params = get_geometry_params_from_json(adjustments);
if !is_geometry_identity(¶ms) {
unwarp_image_geometry(image, params)
} else {
image.clone()
}
}
pub fn apply_flip(image: DynamicImage, horizontal: bool, vertical: bool) -> DynamicImage {
let mut img = image;
if horizontal {
img = img.fliph();
}
if vertical {
img = img.flipv();
}
img
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AutoAdjustmentResults {
pub exposure: f64,
pub contrast: f64,
pub highlights: f64,
pub shadows: f64,
pub vibrancy: f64,
pub vignette_amount: f64,
pub temperature: f64,
pub tint: f64,
pub dehaze: f64,
pub clarity: f64,
pub centre: f64,
pub blacks: f64,
pub whites: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Pod, Zeroable, Default)]
#[repr(C)]
pub struct Point {
x: f32,
y: f32,
_pad1: f32,
_pad2: f32,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Pod, Zeroable, Default)]
#[repr(C)]
pub struct HslColor {
hue: f32,
saturation: f32,
luminance: f32,
_pad: f32,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Pod, Zeroable, Default)]
#[repr(C)]
pub struct ColorGradeSettings {
pub hue: f32,
pub saturation: f32,
pub luminance: f32,
_pad: f32,
}