forked from RomanHargrave/displaycal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolormath.py
3579 lines (2959 loc) · 107 KB
/
colormath.py
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
# -*- coding: utf-8 -*-
"""
Diverse color mathematical functions.
Note:
In most cases, unless otherwise stated RGB is R'G'B' (gamma-compressed)
"""
import colorsys
import logging
import math
import sys
import warnings
def get_transfer_function_phi(alpha, gamma):
return (math.pow(1 + alpha, gamma) * math.pow(gamma - 1, gamma - 1)) / (math.pow(alpha, gamma - 1) * math.pow(gamma, gamma))
LSTAR_E = 216.0 / 24389.0 # Intent of CIE standard, actual CIE standard = 0.008856
LSTAR_K = 24389.0 / 27.0 # Intent of CIE standard, actual CIE standard = 903.3
REC709_K0 = 0.081 # 0.099 / (1.0 / 0.45 - 1)
REC709_P = 4.5 # get_transfer_function_phi(0.099, 1.0 / 0.45)
SMPTE240M_K0 = 0.0913 # 0.1115 / (1.0 / 0.45 - 1)
SMPTE240M_P = 4.0 # get_transfer_function_phi(0.1115, 1.0 / 0.45)
SMPTE2084_M1 = (2610.0 / 4096) * .25
SMPTE2084_M2 = (2523.0 / 4096) * 128
SMPTE2084_C1 = (3424.0 / 4096)
SMPTE2084_C2 = (2413.0 / 4096) * 32
SMPTE2084_C3 = (2392.0 / 4096) * 32
SRGB_K0 = 0.04045 # 0.055 / (2.4 - 1)
SRGB_P = 12.92 # get_transfer_function_phi(0.055, 2.4)
def specialpow(a, b, slope_limit=0):
"""
Wrapper for power, Rec. 601/709, SMPTE 240M, sRGB and L* functions
Positive b = power, -2.4 = sRGB, -3.0 = L*, -240 = SMPTE 240M,
-601 = Rec. 601, -709 = Rec. 709 (Rec. 601 and 709 transfer functions are
identical)
"""
if b >= 0.0:
# Power curve
if a < 0.0:
if slope_limit:
return min(-math.pow(-a, b), a / slope_limit)
return -math.pow(-a, b)
else:
if slope_limit:
return max(math.pow(a, b), a / slope_limit)
return math.pow(a, b)
if a < 0.0:
signScale = -1.0
a = -a
else:
signScale = 1.0
if b in (1.0 / -601, 1.0 / -709):
# XYZ -> RGB, Rec. 601/709 TRC
if a < REC709_K0 / REC709_P:
v = a * REC709_P
else:
v = 1.099 * math.pow(a, 0.45) - 0.099
elif b == 1.0 / -240:
# XYZ -> RGB, SMPTE 240M TRC
if a < SMPTE240M_K0 / SMPTE240M_P:
v = a * SMPTE240M_P
else:
v = 1.1115 * math.pow(a, 0.45) - 0.1115
elif b == 1.0 / -3.0:
# XYZ -> RGB, L* TRC
if a <= LSTAR_E:
v = 0.01 * a * LSTAR_K
else:
v = 1.16 * math.pow(a, 1.0 / 3.0) - 0.16
elif b == 1.0 / -2.4:
# XYZ -> RGB, sRGB TRC
if a <= SRGB_K0 / SRGB_P:
v = a * SRGB_P
else:
v = 1.055 * math.pow(a, 1.0 / 2.4) - 0.055
elif b == 1.0 / -2084:
# XYZ -> RGB, SMPTE 2084 (PQ)
v = ((2413.0 * (a ** SMPTE2084_M1) + 107) /
(2392.0 * (a ** SMPTE2084_M1) + 128)) ** SMPTE2084_M2
elif b == -2.4:
# RGB -> XYZ, sRGB TRC
if a <= SRGB_K0:
v = a / SRGB_P
else:
v = math.pow((a + 0.055) / 1.055, 2.4)
elif b == -3.0:
# RGB -> XYZ, L* TRC
if a <= 0.08: # E * K * 0.01
v = 100.0 * a / LSTAR_K
else:
v = math.pow((a + 0.16) / 1.16, 3.0)
elif b == -240:
# RGB -> XYZ, SMPTE 240M TRC
if a < SMPTE240M_K0:
v = a / SMPTE240M_P
else:
v = math.pow((0.1115 + a) / 1.1115, 1.0 / 0.45)
elif b in (-601, -709):
# RGB -> XYZ, Rec. 601/709 TRC
if a < REC709_K0:
v = a / REC709_P
else:
v = math.pow((a + .099) / 1.099, 1.0 / 0.45)
elif b == -2084:
# RGB -> XYZ, SMPTE 2084 (PQ)
# See https://www.smpte.org/sites/default/files/2014-05-06-EOTF-Miller-1-2-handout.pdf
v = (max(a ** (1.0 / SMPTE2084_M2) - SMPTE2084_C1, 0) /
(SMPTE2084_C2 - SMPTE2084_C3 * a ** (1.0 / SMPTE2084_M2))) ** (1.0 / SMPTE2084_M1)
else:
raise ValueError("Invalid gamma %r" % b)
return v * signScale
def DICOM(j, inverse=False):
if inverse:
log10Y = math.log10(j)
A = 71.498068
B = 94.593053
C = 41.912053
D = 9.8247004
E = 0.28175407
F = -1.1878455
G = -0.18014349
H = 0.14710899
I = -0.017046845
return (A + B * log10Y + C * math.pow(log10Y, 2) +
D * math.pow(log10Y, 3) + E * math.pow(log10Y, 4) +
F * math.pow(log10Y, 5) + G * math.pow(log10Y, 6) +
H * math.pow(log10Y, 7) + I * math.pow(log10Y, 8))
else:
logj = math.log(j)
a = -1.3011877
b = -2.5840191E-2
c = 8.0242636E-2
d = -1.0320229E-1
e = 1.3646699E-1
f = 2.8745620E-2
g = -2.5468404E-2
h = -3.1978977E-3
k = 1.2992634E-4
m = 1.3635334E-3
return ((a + c * logj + e * math.pow(logj, 2) +
g * math.pow(logj, 3) + m * math.pow(logj, 4))
/
(1 + b * logj + d * math.pow(logj, 2) + f * math.pow(logj, 3) +
h * math.pow(logj, 4) + k * math.pow(logj, 5)))
class HLG(object):
"""
Hybrid Log Gamma (HLG) as defined in Rec BT.2100
and BT.2390-4
"""
def __init__(self, black_cdm2=0.0, white_cdm2=1000.0, system_gamma=1.2,
ambient_cdm2=5, rgb_space="Rec. 2020"):
self.black_cdm2 = black_cdm2
self.white_cdm2 = white_cdm2
self.rgb_space = get_rgb_space(rgb_space)
self.system_gamma = system_gamma
self.ambient_cdm2 = ambient_cdm2
@property
def gamma(self):
""" System gamma for nominal peak luminance and ambient """
# Adjust system gamma for peak luminance != 1000 cd/m2 (extended model
# described in BT.2390-4)
K = 1.111
gamma = self.system_gamma * K ** math.log(self.white_cdm2 / 1000.0, 2)
if self.ambient_cdm2 > 0:
# Adjust system gamma for ambient surround != 5 cd/m2 (BT.2390-4)
u = 0.98
gamma *= u ** math.log(self.ambient_cdm2 / 5.0, 2)
return gamma
def oetf(self, v, inverse=False):
"""
Hybrid Log Gamma (HLG) OETF
Relative scene linear light to non-linear HLG signal, or inverse
Input domain 0..1
Output range 0..1
"""
if v == 1:
return 1.0
a = 0.17883277
b = 1 - 4 * a
c = 0.5 - a * math.log(4 * a)
if inverse:
# Non-linear HLG signal to relative scene linear light
if 0 <= v <= 1 / 2.:
v = v ** 2 / 3.
else:
v = (math.exp((v - c) / a) + b) / 12.
else:
# Relative scene linear light to non-linear HLG signal
if 0 <= v <= 1 / 12.:
v = math.sqrt(3 * v)
else:
v = a * math.log(12 * v - b) + c
return v
def eotf(self, RGB, inverse=False, apply_black_offset=True):
"""
Hybrid Log Gamma (HLG) EOTF
Non-linear HLG signal to display light, or inverse
Input domain 0..1
Output range 0..1
"""
if isinstance(RGB, (float, int)):
R, G, B = (RGB,) * 3
else:
R, G, B = RGB
if inverse:
# Display light -> relative scene linear light -> HLG signal
R, G, B = (self.oetf(v) for v in self.ootf((R, G, B), True,
apply_black_offset))
else:
# HLG signal -> relative scene linear light -> display light
R, G, B = self.ootf([self.oetf(v, True) for v in (R, G, B)], False,
apply_black_offset)
return G if isinstance(RGB, (float, int)) else (R, G, B)
def ootf(self, RGB, inverse=False, apply_black_offset=True):
"""
Hybrid Log Gamma (HLG) OOTF
Relative scene linear light to display light, or inverse
Input domain 0..1
Output range 0..1
"""
if isinstance(RGB, (float, int)):
R, G, B = (RGB,) * 3
else:
R, G, B = RGB
if apply_black_offset:
black_cdm2 = float(self.black_cdm2)
else:
black_cdm2 = 0
alpha = (self.white_cdm2 - black_cdm2) / self.white_cdm2
beta = black_cdm2 / self.white_cdm2
Y = 0.2627 * R + 0.6780 * G + 0.0593 * B
if inverse:
if Y > beta:
R, G, B = (((Y - beta) / alpha) ** ((1 - self.gamma) / self.gamma) *
((v - beta) / alpha) for v in (R, G, B))
else:
R, G, B = 0, 0, 0
else:
if Y:
Y **= (self.gamma - 1)
R, G, B = (alpha * Y * E + beta for E in (R, G, B))
return G if isinstance(RGB, (float, int)) else (R, G, B)
def RGB2XYZ(self, R, G, B, apply_black_offset=True):
""" Non-linear HLG signal to display XYZ """
X, Y, Z = self.rgb_space[-1] * [self.oetf(v, True) for v in (R, G, B)]
X, Y, Z = (max(v, 0) for v in (X, Y, Z))
Yy = self.ootf(Y, apply_black_offset=False)
if Y:
X, Y, Z = (v / Y * Yy for v in (X, Y, Z))
else:
X, Y, Z = (v * Yy for v in self.rgb_space[1])
if apply_black_offset:
beta = self.ootf(0)
bp_out = [v * beta for v in self.rgb_space[1]]
X, Y, Z = apply_bpc(X, Y, Z, (0, 0, 0), bp_out, self.rgb_space[1])
return X, Y, Z
def XYZ2RGB(self, X, Y, Z, apply_black_offset=True):
""" Display XYZ to non-linear HLG signal """
if apply_black_offset:
beta = self.ootf(0)
bp_in = [v * beta for v in self.rgb_space[1]]
X, Y, Z = apply_bpc(X, Y, Z, bp_in, (0, 0, 0), self.rgb_space[1])
Yy = self.ootf(Y, True, apply_black_offset=False)
if Y:
X, Y, Z = (v / Y * Yy for v in (X, Y, Z))
R, G, B = self.rgb_space[-1].inverted() * (X, Y, Z)
R, G, B = (max(v, 0) for v in (R, G, B))
R, G, B = [self.oetf(v) for v in (R, G, B)]
return R, G, B
rgb_spaces = {
# http://brucelindbloom.com/WorkingSpaceInfo.html
# ACES: https://github.com/ampas/aces-dev/blob/master/docs/ACES_1.0.1.pdf?raw=true
# Adobe RGB: http://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
# DCI P3: http://www.hp.com/united-states/campaigns/workstations/pdfs/lp2480zx-dci--p3-emulation.pdf
# http://dcimovies.com/specification/DCI_DCSS_v12_with_errata_2012-1010.pdf
# Rec. 2020: http://en.wikipedia.org/wiki/Rec._2020
#
# name gamma white primaries
# point Rx Ry RY Gx Gy GY Bx By BY
"ACES": (1.0, (0.95265, 1.0, 1.00883), (0.7347, 0.2653, 0.343961), (0.0000, 1.0000, 0.728164), (0.0001,-0.0770,-0.072125)),
"ACEScg": (1.0, (0.95265, 1.0, 1.00883), (0.7130, 0.2930, 0.272230), (0.1650, 0.8300, 0.674080), (0.1280, 0.0440, 0.053690)),
"Adobe RGB (1998)": (2 + 51 / 256.0, "D65", (0.6400, 0.3300, 0.297361), (0.2100, 0.7100, 0.627355), (0.1500, 0.0600, 0.075285)),
"Apple RGB": (1.8, "D65", (0.6250, 0.3400, 0.244634), (0.2800, 0.5950, 0.672034), (0.1550, 0.0700, 0.083332)),
"Best RGB": (2.2, "D50", (0.7347, 0.2653, 0.228457), (0.2150, 0.7750, 0.737352), (0.1300, 0.0350, 0.034191)),
"Beta RGB": (2.2, "D50", (0.6888, 0.3112, 0.303273), (0.1986, 0.7551, 0.663786), (0.1265, 0.0352, 0.032941)),
"Bruce RGB": (2.2, "D65", (0.6400, 0.3300, 0.240995), (0.2800, 0.6500, 0.683554), (0.1500, 0.0600, 0.075452)),
"CIE RGB": (2.2, "E", (0.7350, 0.2650, 0.176204), (0.2740, 0.7170, 0.812985), (0.1670, 0.0090, 0.010811)),
"ColorMatch RGB": (1.8, "D50", (0.6300, 0.3400, 0.274884), (0.2950, 0.6050, 0.658132), (0.1500, 0.0750, 0.066985)),
# "DCDM X'Y'Z'": (2.6, "E", (1.0000, 0.0000, 0.000000), (0.0000, 1.0000, 1.000000), (0.0000, 0.0000, 0.000000)),
"DCI P3": (2.6, (0.89459, 1.0, 0.95442), (0.6800, 0.3200, 0.209475), (0.2650, 0.6900, 0.721592), (0.1500, 0.0600, 0.068903)),
"DCI P3 D65": (2.6, "D65", (0.6800, 0.3200, 0.209475), (0.2650, 0.6900, 0.721592), (0.1500, 0.0600, 0.068903)),
"Don RGB 4": (2.2, "D50", (0.6960, 0.3000, 0.278350), (0.2150, 0.7650, 0.687970), (0.1300, 0.0350, 0.033680)),
"ECI RGB": (1.8, "D50", (0.6700, 0.3300, 0.320250), (0.2100, 0.7100, 0.602071), (0.1400, 0.0800, 0.077679)),
"ECI RGB v2": (-3.0, "D50", (0.6700, 0.3300, 0.320250), (0.2100, 0.7100, 0.602071), (0.1400, 0.0800, 0.077679)),
"Ekta Space PS5": (2.2, "D50", (0.6950, 0.3050, 0.260629), (0.2600, 0.7000, 0.734946), (0.1100, 0.0050, 0.004425)),
"NTSC 1953": (2.2, "C", (0.6700, 0.3300, 0.298839), (0.2100, 0.7100, 0.586811), (0.1400, 0.0800, 0.114350)),
"PAL/SECAM": (2.2, "D65", (0.6400, 0.3300, 0.222021), (0.2900, 0.6000, 0.706645), (0.1500, 0.0600, 0.071334)),
"ProPhoto RGB": (1.8, "D50", (0.7347, 0.2653, 0.288040), (0.1596, 0.8404, 0.711874), (0.0366, 0.0001, 0.000086)),
"Rec. 709": (-709, "D65", (0.6400, 0.3300, 0.212656), (0.3000, 0.6000, 0.715158), (0.1500, 0.0600, 0.072186)),
"Rec. 2020": (-709, "D65", (0.7080, 0.2920, 0.262694), (0.1700, 0.7970, 0.678009), (0.1310, 0.0460, 0.059297)),
"SMPTE-C": (2.2, "D65", (0.6300, 0.3400, 0.212395), (0.3100, 0.5950, 0.701049), (0.1550, 0.0700, 0.086556)),
"SMPTE 240M": (-240, "D65", (0.6300, 0.3400, 0.212395), (0.3100, 0.5950, 0.701049), (0.1550, 0.0700, 0.086556)),
"sRGB": (-2.4, "D65", (0.6400, 0.3300, 0.212656), (0.3000, 0.6000, 0.715158), (0.1500, 0.0600, 0.072186)),
"Wide Gamut RGB": (2.2, "D50", (0.7350, 0.2650, 0.258187), (0.1150, 0.8260, 0.724938), (0.1570, 0.0180, 0.016875))
}
def get_cat_matrix(cat="Bradford"):
if isinstance(cat, basestring):
cat = cat_matrices[cat]
if not isinstance(cat, Matrix3x3):
cat = Matrix3x3(cat)
return cat
def cbrt(x):
return math.pow(x, 1.0 / 3.0) if x >= 0 else -math.pow(-x, 1.0 / 3.0)
def var(a):
""" Variance """
s = 0.0
l = len(a)
while l:
l -= 1
s += a[l]
l = len(a)
m = s / l
s = 0.0
while l:
l -= 1
s += (a[l] - m) ** 2
return s / len(a)
def XYZ2LMS(X, Y, Z, cat="Bradford"):
""" Convert from XYZ to cone response domain """
cat = get_cat_matrix(cat)
p, y, b = cat * [X, Y, Z]
return p, y, b
def LMS_wp_adaption_matrix(whitepoint_source=None,
whitepoint_destination=None,
cat="Bradford"):
""" Prepare a matrix to match the whitepoints in cone response domain """
# chromatic adaption
# based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
# cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
# 'Von Kries', 'XYZ Scaling', see cat_matrices), defaults to 'Bradford'
cat = get_cat_matrix(cat)
XYZWS = get_whitepoint(whitepoint_source)
XYZWD = get_whitepoint(whitepoint_destination)
if XYZWS[1] <= 1.0 and XYZWD[1] > 1.0:
# make sure the scaling is identical
XYZWD = [v / XYZWD[1] * XYZWS[1] for v in XYZWD]
if XYZWD[1] <= 1.0 and XYZWS[1] > 1.0:
# make sure the scaling is identical
XYZWS = [v / XYZWS[1] * XYZWD[1] for v in XYZWS]
Ls, Ms, Ss = XYZ2LMS(XYZWS[0], XYZWS[1], XYZWS[2], cat)
Ld, Md, Sd = XYZ2LMS(XYZWD[0], XYZWD[1], XYZWD[2], cat)
return Matrix3x3([[Ld/Ls, 0, 0], [0, Md/Ms, 0], [0, 0, Sd/Ss]])
def wp_adaption_matrix(whitepoint_source=None, whitepoint_destination=None,
cat="Bradford"):
"""
Prepare a matrix to match the whitepoints in cone response doamin and
transform back to XYZ
"""
# chromatic adaption
# based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
# cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
# 'Von Kries', 'XYZ Scaling', see cat_matrices), defaults to 'Bradford'
cachehash = (tuple(whitepoint_source) if isinstance(whitepoint_source,
(list, tuple))
else whitepoint_source,
tuple(whitepoint_destination) if isinstance(whitepoint_destination,
(list, tuple))
else whitepoint_destination,
cat if isinstance(cat, basestring) else id(cat))
if cachehash in wp_adaption_matrix.cache:
return wp_adaption_matrix.cache[cachehash]
cat = get_cat_matrix(cat)
wpam = cat.inverted() * LMS_wp_adaption_matrix(whitepoint_source,
whitepoint_destination,
cat) * cat
wp_adaption_matrix.cache[cachehash] = wpam
return wpam
wp_adaption_matrix.cache = {}
def adapt(X, Y, Z, whitepoint_source=None, whitepoint_destination=None,
cat="Bradford"):
"""
Transform XYZ under source illuminant to XYZ under destination illuminant
"""
# chromatic adaption
# based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
# cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
# 'Von Kries', 'XYZ Scaling', see cat_matrices), defaults to 'Bradford'
return wp_adaption_matrix(whitepoint_source, whitepoint_destination,
cat) * (X, Y, Z)
def apply_bpc(X, Y, Z, bp_in=None, bp_out=None, wp_out="D50", weight=False,
pin_chromaticity=False):
"""
Apply black point compensation
"""
if not bp_in:
bp_in = (0, 0, 0)
if not bp_out:
bp_out = (0, 0, 0)
wp_out = get_whitepoint(wp_out)
if weight:
L = XYZ2Lab(*[v * 100 for v in (X, Y, Z)])[0]
bp_in_Lab = XYZ2Lab(*[v * 100 for v in bp_in])
bp_out_Lab = XYZ2Lab(*[v * 100 for v in bp_out])
vv = (L - bp_in_Lab[0]) / (100.0 - bp_in_Lab[0]) # 0 at bp, 1 at wp
vv = 1.0 - vv
if vv < 0.0:
vv = 0.0
elif vv > 1.0:
vv = 1.0
vv = math.pow(vv, min(40.0, 40.0 / (max(bp_in_Lab[0],
bp_out_Lab[0]) or 1.0)))
bp_in = Lab2XYZ(*[v * vv for v in bp_in_Lab])
bp_out = Lab2XYZ(*[v * vv for v in bp_out_Lab])
if pin_chromaticity:
XYZ = [Y]
x, y = XYZ2xyY(X, Y, Z, wp_out)[:2]
bp_in = bp_in[1:2]
bp_out = bp_out[1:2]
wp_out = wp_out[1:2]
else:
XYZ = [X, Y, Z]
for i, v in enumerate(XYZ):
XYZ[i] = ((wp_out[i] - bp_out[i]) * v - wp_out[i] * (bp_in[i] - bp_out[i])) / (wp_out[i] - bp_in[i])
if pin_chromaticity:
XYZ = xyY2XYZ(x, y, XYZ[0])
return XYZ
def avg(*args):
return float(sum(args)) / len(args)
def blend_ab(X, Y, Z, bp, wp, power=40.0, signscale=1):
if Y < 0:
return 0, 0, 0
L, a, b = XYZ2Lab(X, Y, Z, whitepoint=wp)
bpL, bpa, bpb = XYZ2Lab(*bp, whitepoint=wp)
if bpL == 100:
raise ValueError("Black L* is 100!")
vv = (L - bpL) / (100.0 - bpL) # 0 at bp, 1 at wp
vv = 1.0 - vv # 1 at bp, 0 at wp
if vv < 0.0:
vv = 0.0
elif vv > 1.0:
vv = 1.0
vv = math.pow(vv, power) * signscale
a += vv * bpa
b += vv * bpb
return Lab2XYZ(L, a, b, whitepoint=wp)
def blend_blackpoint(X, Y, Z, bp_in=None, bp_out=None, wp=None, power=40.0,
pin_chromaticity=False):
"""
Blend to destination black as L approaches black, optionally compensating
for input black first
"""
wp = get_whitepoint(wp)
for i, bp in enumerate((bp_in, bp_out)):
if not bp or tuple(bp) == (0, 0, 0):
continue
bp_wp = tuple(v / wp[1] * bp[1] for v in wp)
if i == 0:
X, Y, Z = blend_ab(X, Y, Z, bp, wp, power, -1)
X, Y, Z = apply_bpc(X, Y, Z, bp_wp, None, wp, pin_chromaticity)
else:
X, Y, Z = apply_bpc(X, Y, Z, None, bp_wp, wp, pin_chromaticity)
X, Y, Z = blend_ab(X, Y, Z, bp, wp, power, 1)
return X, Y, Z
def interp(x, xp, fp, left=None, right=None):
"""
One-dimensional linear interpolation similar to numpy.interp
Values do NOT have to be monotonically increasing
interp(0, [0, 0], [0, 1]) will return 0
"""
if not isinstance(x, (int, long, float, complex)):
yi = []
for n in x:
yi.append(interp(n, xp, fp, left, right))
return yi
if x in xp:
return fp[xp.index(x)]
elif x < xp[0]:
return fp[0] if left is None else left
elif x > xp[-1]:
return fp[-1] if right is None else right
else:
# Interpolate
lower = 0
higher = len(fp) - 1
for i, v in enumerate(xp):
if v < x and i > lower:
lower = i
elif v > x and i < higher:
higher = i
step = float(x - xp[lower])
steps = (xp[higher] - xp[lower]) / step
return fp[lower] + (fp[higher] - fp[lower]) / steps
def interp_resize(iterable, new_size, use_numpy=False):
""" Change size of iterable through linear interpolation """
result = []
x_new = range(len(iterable))
interp = Interp(x_new, iterable, use_numpy=use_numpy)
for i in xrange(new_size):
result.append(interp(i / (new_size - 1.0) * (len(iterable) - 1.0)))
return result
def interp_fill(xp, fp, new_size, use_numpy=False):
""" Fill missing points by interpolation """
result = []
last = xp[-1]
interp = Interp(xp, fp, use_numpy=use_numpy)
for i in xrange(new_size):
result.append(interp(i / (new_size - 1.0) * last))
return result
def smooth_avg(values, passes=1, window=None, protect=None):
"""
Smooth values (moving average).
passses Number of passes
window Tuple or list containing weighting factors. Its length
determines the size of the window to use.
Defaults to (1.0, 1.0, 1.0)
"""
if not window or len(window) < 3 or len(window) % 2 != 1:
if window:
warnings.warn("Invalid window %r, size %i - using default (1, 1, 1)" %
(window, len(window)), Warning)
window = (1.0, 1.0, 1.0)
for x in xrange(0, passes):
data = []
for j, v in enumerate(values):
tmpwindow = window
if not protect or j not in protect:
while j > 0 and j < len(values) - 1 and len(tmpwindow) >= 3:
tl = (len(tmpwindow) - 1) / 2
# print j, tl, tmpwindow
if tl > 0 and j - tl >= 0 and j + tl <= len(values) - 1:
windowslice = values[j - tl:j + tl + 1]
windowsize = 0
for k, weight in enumerate(tmpwindow):
windowsize += float(weight) * windowslice[k]
v = windowsize / sum(tmpwindow)
break
else:
tmpwindow = tmpwindow[1:-1]
data.append(v)
values = data
return data
def compute_bpc(bp_in, bp_out):
"""
Black point compensation. Implemented as a linear scaling in XYZ.
Black points should come relative to the white point. Fills and
returns a matrix/offset element.
[matrix]*bp_in + offset = bp_out
[matrix]*D50 + offset = D50
"""
# This is a linear scaling in the form ax+b, where
# a = (bp_out - D50) / (bp_in - D50)
# b = - D50* (bp_out - bp_in) / (bp_in - D50)
D50 = get_standard_illuminant("D50")
tx = bp_in[0] - D50[0]
ty = bp_in[1] - D50[1]
tz = bp_in[2] - D50[2]
ax = (bp_out[0] - D50[0]) / tx
ay = (bp_out[1] - D50[1]) / ty
az = (bp_out[2] - D50[2]) / tz
bx = - D50[0] * (bp_out[0] - bp_in[0]) / tx
by = - D50[1] * (bp_out[1] - bp_in[1]) / ty
bz = - D50[2] * (bp_out[2] - bp_in[2]) / tz
matrix = Matrix3x3([[ax, 0, 0],
[0, ay, 0],
[0, 0, az]])
offset = [bx, by, bz]
return matrix, offset
def delta(L1, a1, b1, L2, a2, b2, method="1976", p1=None, p2=None, p3=None,
cie94_use_symmetric_chrominance=True):
"""
Compute the delta of two samples
CIE 1994 & CMC calculation code derived from formulas on
www.brucelindbloom.com
CIE 1994 code uses some alterations seen on
www.farbmetrik-gall.de/cielab/korrcielab/cie94.html
(see notes in code below)
CIE 2000 calculation code derived from Excel spreadsheet available at
www.ece.rochester.edu/~gsharma/ciede2000
method: either "CIE94", "CMC", "CIE2K" or "CIE76"
(default if method is not set)
p1, p2, p3 arguments have different meaning for each calculation method:
CIE 1994: If p1 is not None, calculation will be adjusted for
textiles, otherwise graphics arts (default if p1 is not set)
CMC(l:c): p1 equals l (lightness) weighting factor and p2 equals c
(chroma) weighting factor.
Commonly used values are CMC(1:1) for perceptability
(default if p1 and p2 are not set) and CMC(2:1) for
acceptability
CIE 2000: p1 becomes kL (lightness) weighting factor, p2 becomes
kC (chroma) weighting factor and p3 becomes kH (hue)
weighting factor (all three default to 1 if not set)
"""
if isinstance(method, basestring):
method = method.lower()
else:
method = str(int(method))
if method in ("94", "1994", "cie94", "cie1994"):
textiles = p1
dL = L2 - L1
C1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
C2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
dC = C2 - C1
dH2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dC, 2)
dH = math.sqrt(dH2) if dH2 > 0 else 0
SL = 1.0
K1 = 0.048 if textiles else 0.045
K2 = 0.014 if textiles else 0.015
if cie94_use_symmetric_chrominance:
C_ = math.sqrt(C1 * C2)
else:
C_ = C1
SC = 1.0 + K1 * C_
SH = 1.0 + K2 * C_
KL = 2.0 if textiles else 1.0
KC = 1.0
KH = 1.0
dLw, dCw, dHw = dL / (KL * SL), dC / (KC * SC), dH / (KH * SH)
dE = math.sqrt(math.pow(dLw, 2) + math.pow(dCw, 2) + math.pow(dHw, 2))
elif method in ("cmc(2:1)", "cmc21", "cmc(1:1)", "cmc11", "cmc"):
if method in ("cmc(2:1)", "cmc21"):
p1 = 2.0
l = p1 if isinstance(p1, (float, int)) else 1.0
c = p2 if isinstance(p2, (float, int)) else 1.0
dL = L2 - L1
C1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
C2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
dC = C2 - C1
dH2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dC, 2)
dH = math.sqrt(dH2) if dH2 > 0 else 0
SL = 0.511 if L1 < 16 else (0.040975 * L1) / (1 + 0.01765 * L1)
SC = (0.0638 * C1) / (1 + 0.0131 * C1) + 0.638
F = math.sqrt(math.pow(C1, 4) / (math.pow(C1, 4) + 1900.0))
H1 = math.degrees(math.atan2(b1, a1)) + (0 if b1 >= 0 else 360.0)
T = 0.56 + abs(0.2 * math.cos(math.radians(H1 + 168.0))) if 164 <= H1 and H1 <= 345 else 0.36 + abs(0.4 * math.cos(math.radians(H1 + 35)))
SH = SC * (F * T + 1 - F)
dLw, dCw, dHw = dL / (l * SL), dC / (c * SC), dH / SH
dE = math.sqrt(math.pow(dLw, 2) + math.pow(dCw, 2) + math.pow(dHw, 2))
elif method in ("00", "2k", "2000", "cie00", "cie2k", "cie2000"):
pow25_7 = math.pow(25, 7)
k_L = p1 if isinstance(p1, (float, int)) else 1.0
k_C = p2 if isinstance(p2, (float, int)) else 1.0
k_H = p3 if isinstance(p3, (float, int)) else 1.0
C1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
C2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
C_avg = avg(C1, C2)
G = .5 * (1 - math.sqrt(math.pow(C_avg, 7) / (math.pow(C_avg, 7) + pow25_7)))
L1_ = L1
a1_ = (1 + G) * a1
b1_ = b1
L2_ = L2
a2_ = (1 + G) * a2
b2_ = b2
C1_ = math.sqrt(math.pow(a1_, 2) + math.pow(b1_, 2))
C2_ = math.sqrt(math.pow(a2_, 2) + math.pow(b2_, 2))
h1_ = 0 if a1_ == 0 and b1_ == 0 else math.degrees(math.atan2(b1_, a1_)) + (0 if b1_ >= 0 else 360.0)
h2_ = 0 if a2_ == 0 and b2_ == 0 else math.degrees(math.atan2(b2_, a2_)) + (0 if b2_ >= 0 else 360.0)
dh_cond = 1.0 if h2_ - h1_ > 180 else (2.0 if h2_ - h1_ < -180 else 0)
dh_ = h2_ - h1_ if dh_cond == 0 else (h2_ - h1_ - 360.0 if dh_cond == 1 else h2_ + 360.0 - h1_)
dL_ = L2_ - L1_
dL = dL_
dC_ = C2_ - C1_
dC = dC_
dH_ = 2 * math.sqrt(C1_ * C2_) * math.sin(math.radians(dh_ / 2.0))
dH = dH_
L__avg = avg(L1_, L2_)
C__avg = avg(C1_, C2_)
h__avg_cond = 3.0 if C1_ * C2_ == 0 else (0 if abs(h2_ - h1_) <= 180 else (1.0 if h2_ + h1_ < 360 else 2.0))
h__avg = h1_ + h2_ if h__avg_cond == 3 else (avg(h1_, h2_) if h__avg_cond == 0 else (avg(h1_, h2_) + 180.0 if h__avg_cond == 1 else avg(h1_, h2_) - 180.0))
AB = math.pow(L__avg - 50.0, 2) # (L'_ave-50)^2
S_L = 1 + .015 * AB / math.sqrt(20.0 + AB)
S_C = 1 + .045 * C__avg
T = (1 - .17 * math.cos(math.radians(h__avg - 30.0)) + .24 * math.cos(math.radians(2.0 * h__avg)) + .32 * math.cos(math.radians(3.0 * h__avg + 6.0))
- .2 * math.cos(math.radians(4 * h__avg - 63.0)))
S_H = 1 + .015 * C__avg * T
dTheta = 30.0 * math.exp(-1 * math.pow((h__avg - 275.0) / 25.0, 2))
R_C = 2.0 * math.sqrt(math.pow(C__avg, 7) / (math.pow(C__avg, 7) + pow25_7))
R_T = -math.sin(math.radians(2.0 * dTheta)) * R_C
AJ = dL_ / S_L / k_L # dL' / k_L / S_L
AK = dC_ / S_C / k_C # dC' / k_C / S_C
AL = dH_ / S_H / k_H # dH' / k_H / S_H
dLw, dCw, dHw = AJ, AK, AL
dE = math.sqrt(math.pow(AJ, 2) + math.pow(AK, 2) + math.pow(AL, 2) + R_T * AK * AL)
else:
# dE 1976
dL = L2 - L1
C1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
C2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
dC = C2 - C1
dH2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dC, 2)
dH = math.sqrt(dH2) if dH2 > 0 else 0
dLw, dCw, dHw = dL, dC, dH
dE = math.sqrt(math.pow(dL, 2) + math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2))
return {"E": dE,
"L": dL,
"C": dC,
"H": dH,
"a": a1 - a2,
"b": b1 - b2,
# Weighted
"Lw": dLw,
"Cw": dCw,
"Hw": dHw}
def XYZ2Lab_delta(X1, Y1, Z1, X2, Y2, Z2, method="76", whitepoint1="D50",
whitepoint2="D50", whitepoint_reference="D50", cat="Bradford"):
whitepoint1 = get_whitepoint(whitepoint1)
whitepoint2 = get_whitepoint(whitepoint2)
whitepoint_reference = get_whitepoint(whitepoint_reference)
if whitepoint1 != whitepoint_reference:
X1, Y1, Z1 = adapt(X1, Y1, Z1, whitepoint1, whitepoint_reference, cat)
if whitepoint2 != whitepoint_reference:
X2, Y2, Z2 = adapt(X2, Y2, Z2, whitepoint2, whitepoint_reference, cat)
L1, a1, b1 = XYZ2Lab(X1, Y1, Z1, whitepoint_reference)
L2, a2, b2 = XYZ2Lab(X2, Y2, Z2, whitepoint_reference)
logging.debug("L*a*b*[1] %.4f %.4f %.4f L*a*b*[2] %.4f %.4f %.4f" %
(L1, a1, b1, L2, a2, b2))
return delta(L1, a1, b1, L2, a2, b2, method)
def is_similar_matrix(matrix1, matrix2, digits=3):
""" Compare two matrices and check if they are the same
up to n digits after the decimal point """
return matrix1.rounded(digits) == matrix2.rounded(digits)
def is_equal(values1, values2, quantizer=lambda v: round(v, 4)):
""" Compare two sets of values and check if they are the same
after applying quantization """
return [quantizer(v) for v in values1] == [quantizer(v) for v in values2]
def four_color_matrix(XrR, YrR, ZrR, XrG, YrG, ZrG, XrB, YrB, ZrB, XrW, YrW, ZrW,
XmR, YmR, ZmR, XmG, YmG, ZmG, XmB, YmB, ZmB, XmW, YmW, ZmW,
Y_correction=True):
"""
Four-Color Matrix Method for Correction of Tristimulus Colorimeters
Based on paper published in Proc., IS&T Fifth Color Imaging Conference,
301-305 (1997) and IS&T Sixth Color Imaging Conference (1998).
"""
XYZ = locals()
xyz = {}
M = {}
k = {}
for s in "mr":
xyz[s] = {}
for color in "RGBW":
X, Y, Z = (XYZ[component + s + color] for component in "XYZ")
x, y = XYZ2xyY(X, Y, Z)[:2]
xyz[s][color] = x, y, 1 - x - y
M[s] = Matrix3x3([xyz[s][color] for color in "RGB"]).transposed()
k[s] = M[s].inverted() * xyz[s]["W"]
M[s + "RGB"] = M[s] * Matrix3x3([[k[s][0], 0, 0],
[0, k[s][1], 0],
[0, 0, k[s][2]]])
R = M["rRGB"] * M["mRGB"].inverted()
if Y_correction:
# The Y calibration factor kY is obtained as the ratio of the reference
# luminance value to the matrix-corrected Y value, as defined in
# Four-Color Matrix Method for Correction of Tristimulus Colorimeters –
# Part 2
MW = XmW, YmW, ZmW
kY = YrW / (R * MW)[1]
R[:] = [[kY * v for v in row] for row in R]
return R
def get_gamma(values, scale=1.0, vmin=0.0, vmax=1.0, average=True, least_squares=False):
""" Return average or least squares gamma or a list of gamma values """
if least_squares:
logxy = []
logx2 = []
else:
gammas = []
vmin /= scale
vmax /= scale
for x, y in values:
x /= scale
y = (y / scale - vmin) * (vmax + vmin)
if x > 0 and x < 1 and y > 0:
if least_squares:
logxy.append(math.log(x) * math.log(y))
logx2.append(math.pow(math.log(x), 2))
else:
gammas.append(math.log(y) / math.log(x))
if average or least_squares:
if least_squares:
if not logxy or not logx2:
return 0
return sum(logxy) / sum(logx2)
else:
if not gammas:
return 0
return sum(gammas) / len(gammas)
else:
return gammas
def guess_cat(chad, whitepoint_source=None, whitepoint_destination=None):
""" Try and guess the chromatic adaption transform used in a chromatic
adaption matrix as found in an ICC profile's 'chad' tag """
if chad == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]:
# Cannot figure out CAT from identity chad
return
for cat in cat_matrices:
if is_similar_matrix((chad * cat_matrices[cat].inverted() *
LMS_wp_adaption_matrix(whitepoint_destination,
whitepoint_source,
cat)).inverted(),
cat_matrices[cat], 2):
return cat
def CIEDCCT2xyY(T, scale=1.0):
"""
Convert from CIE correlated daylight temperature to xyY.
T = temperature in Kelvin.
Based on formula from http://brucelindbloom.com/Eqn_T_to_xy.html
"""
if isinstance(T, basestring):
# Assume standard illuminant, e.g. "D50"
return XYZ2xyY(*get_standard_illuminant(T, scale=scale))
if not (2500 <= T <= 25000):
# Lower limit of 2500 is consistent with Argyll xicc/xspect.c daylight_il
# Actual usable lower limit lies at roughly 2244
return None
if T < 4000:
# Only accurate down to about 4000
warnings.warn("Daylight CCT is only accurate down to about 4000 K",
Warning)
if T <= 7000:
xD = (((-4.607 * math.pow(10, 9)) / math.pow(T, 3))
+ ((2.9678 * math.pow(10, 6)) / math.pow(T, 2))
+ ((0.09911 * math.pow(10, 3)) / T)
+ 0.244063)
else:
xD = (((-2.0064 * math.pow(10, 9)) / math.pow(T, 3))
+ ((1.9018 * math.pow(10, 6)) / math.pow(T, 2))
+ ((0.24748 * math.pow(10, 3)) / T)
+ 0.237040)
yD = -3 * math.pow(xD, 2) + 2.87 * xD - 0.275
return xD, yD, scale
def CIEDCCT2XYZ(T, scale=1.0):
"""
Convert from CIE correlated daylight temperature to XYZ.
T = temperature in Kelvin.
"""
xyY = CIEDCCT2xyY(T, scale)
if xyY:
return xyY2XYZ(*xyY)
# cLUT Input value tweaks to make Video encoded black land on
# 65 res grid nodes, which should help 33 and 17 res cLUTs too
def cLUT65_to_VidRGB(v, size=65):
if v <= 236.0 / 256:
# Scale up to near black point
return v * 256.0 / 255
else:
return 1 - (1 - v) * (1 - 236.0 / 255) / (1 - 236.0 / 256)
def VidRGB_to_cLUT65(v, size=65):
if v <= 236.0 / 255.0:
return v * 255.0 / 256
else:
return 1 - (1 - v) * (1 - 236.0 / 256) / (1 - 236.0 / 255)
def VidRGB_to_eeColor(v):
return v * 255.0/256.0
def eeColor_to_VidRGB(v):
return v * 256.0/255.0
def DIN992Lab(L99, a99, b99, kCH=1.0, kE=1.0):
C99, H99 = DIN99familyab2DIN99CH(a99, b99)
return DIN99familyLCH2Lab(L99, C99, H99, 0, 105.51, .0158, 16, .7,
1 / (0.045 * kCH * kE), 0.045, kE, 0)
def DIN99b2Lab(L99, a99, b99):
C99, H99 = DIN99familyab2DIN99CH(a99, b99)
return DIN99familyLCH2Lab(L99, C99, H99, 0, 303.67, .0039, 26, .83, 23, .075)
def DIN99o2Lab(L99, a99, b99, kCH=1.0, kE=1.0):
C99, H99 = DIN99familyab2DIN99CH(a99, b99)
return DIN99familyLCH2Lab(L99, C99, H99, 0, 303.67, .0039, 26, .83,
1 / (0.0435 * kCH * kE), .075, kE)
def DIN99bLCH2Lab(L99, C99, H99):
return DIN99familyLCH2Lab(L99, C99, H99, 0, 303.67, .0039, 26, .83, 23, .075)